I have a strange problem by initiating a class object.
The problem is as strange as well not easily reproducible. However I will try to give an indicating example.
I have inheritance classes.
class BarClass {
public:
BarClass() {
...
}
BarClass(int i, int j) {
...
}
void doSomething() { ... }
};
class FooClass : public BarClass {
public:
FooClass() {
}
FooClass(int i, int j) : BarClass(i,j) {
...
}
};
Sometime if I initiate objects with following manner, I will get segmentation fault error by initialization.
FooClass foo1;
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
If I use explicit pointer new, then it is OK..
FooClass *foo1= new FooClass();
foo1->doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
The following code will give me a compiler error on line 2.
FooClass foo1();
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
how should I properly initiate a object, especially when it has default constructor and those with arguments.
Your last issue first…
does not create an object of type FooClass but declares a function called foo1() that takes no parameters and returns a FooClass. Remove the parentheses to create the instance as you did in the first code sample.
why you get a segmmentation fault may have something to do with your destructor which we can’t see, and this doesn’t get invoked in your second example which leaks.