"Nafai" <na*******@yahoo.es> wrote in message
news:Cj***********************@telenews.teleline.e s...
Hello. I want to do something like this:
class A { // It's virtual
protected:
float* data;
int n;
public:
A(int a);
virtual float* createData();
//...
};
class B : public A {
public:
float* createData();
};
A::A(int a)
{
n=a;
data=createData();
}
float* B::createData()
{ // ... // }
That is, to construct a derived class of A, I only need to define
createData. But I get compiling errors. What's the problem?
There are several rules related to constructors.
First part of the problem:
A default constructor is generated by the compiler for any class that has no
constructor declared. If you declare a constructor of the class (see A( int
a)), there will be no default constructor generated anymore. If you need the
default constructor you should declare and implement it explicitly.
The second part of the problem:
In the derived class, if you don't call explicitly the base class'
constructor (like B(): A( 10) {} ) the compiler tries to generate code for
calling the default constructor of the base class. Since A has no default
constructor, the compiler fails and a compiler error is generated.
The third part of the problem:
B has no constructor declared, so a default constructor is generated by the
compiler (see First part of the problem). That generated default constructor
calls the default constructor of the class A (see the second part of the
problem), which doesn't exist (see First part of the problem :), so a
compiler error is generated.
The conclusion:
Define the default constructor for B and call the constructor of A.
Something like this:
B::B(): A( 0) { }
Br/
Catalin