0

in the following code

class obj
{
protected:
int somedata;

public:
obj (int x)
{somedata=x;}
};

i want to make another child class form this one and inherits the constructor
plz help

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by caut_baia
0

Hello helmyano,
Constructors are not inherited. You have to define a constructor in the derived class also. The base class default constructor (the constructor with no parameters) and its destructor are always called when a new object of a derived class is created or destroyed.

Edited by Arbus: n/a

1

When you inherit from a base class all of it's members and functions are inherited so a derived class will contain 'somedata' but will not be initialized.For that you must explicitly call the base class's user defined constructor in the initialization list of the derived class's constructor.

class A  {
protected:
   int somedata;
public:
   A (int s) : somedata(s) {}
   A () {}
   ~A () {}
 };

class B : public A {
public:
   B (int s) : A(s) {} //B's 'somedata' member will hold the value of 's'
   B () {}
   ~B () {}
 };

Edited by caut_baia: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.