63 829
Assignments Done
99,3%
Successfully Done
In August 2018

Answer to Question #20263 in C++ for roneey

Question #20263
when the constructor for a derived class compulsary?
Expert's answer
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 first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions