Answer to Question #20263 in C++ for roneey

Question #20263
when the constructor for a derived class compulsary?
1
Expert's answer
2012-12-11T08:51:07-0500
The constructor of a derived class is compulsory in the following cases:
1. If the class (it could be a simple class, not a child) has no default constructor
but has a constructor with parameters. For example the following code
will produce compilation error:
class Parent {};
class Child : Parent
{
public:
Child(int x) { ... }
};

void main()
{
Child a;
}
If you don't define any class constructors, compiler will create the default one for you,
which takes no arguments and initializes all class fields with default values.
But if you define a constructor with parameters you must also define your own
default constructor implementation.

2. If parent class has no default constructor but has only constructors with parameters.
So the following code will also produce an error:
class Parent
{
public:
Parent(int x) { ... }
};

class Child : Parent
{
public:
Child() { ... }
Child(int y) { ... }
};

void main()
{
Child b;
Child c(4);
}
because the Child() and Child(int y) constructors try to call the parent class default constructor
implicitly and parent class has no default constructor defined (see case 1).
So you have to call the available parent class constructor explicitly:
class Parent
{
public:
Parent(int x) { ... }
};

class Child : Parent
{
public:
Child() : Parent(5) { ... }
Child(int y) : Parent(y) { ... }
};
or just define the parent class default constructor:
class Parent
{
public:
Parent() { ... }
Parent(int x) { ... }
};

class Child : Parent
{
public:
Child() { ... }
Child(int y) { ... }
};

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS