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

Recommended Answers

All 2 Replies

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.

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 () {}
 };
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.