Inherited constructors

I'm learning inheritance in C++, and I ran into a little problem.

Lets say I have a base class:
1
2
3
4
5
6
7
8
9
10
11
12
class BaseDialog{
const char *message;
const char *title;
int x,y;
public:
    BaseDialog(const char *Message, const char *Title, int X, int Y){
        message=Message;
        title=Title;
        x=X;
        y=Y;
    }
};

and I want to make an child of that class:
1
2
3
4
class YesNoDialog : public BaseDialog{
const char *message;
const char *title;
};

That example might be confusing, basically how would I be able to make the constructor so that it can initialize all the variables required for the base class, and some extra for the child?

If I add a default constructor to the parent class then some variables will be left uninitialized.

~~~
Also, in the above example the child cant access the parent private members. why does that happen?
Also, in the above example the child cant access the parent private members. why does that happen?

Make them protected. By default they are private.

Make a derived class constructor using parent class constructor in an initialization list:
1
2
3
4
5
6
7
8
9
10
class YesNoDialog : public BaseDialog{
const char *message;
const char *title;
public:
YesNoDialog (const char *Message, const char *Title, int X, int Y, int extra_param) :
  BaseDialog(const char *Message, const char *Title, int X, int Y)
  {
     inner_field = extra_param;
  }
};
Also, in the above example the child cant access the parent private members. why does that happen?


It would defeat the point of encapsulation if you could simply gain access to a class private members
simply by deriving a class from it.


Also, derived classes are supposed to add value.
Having the derived class have the same parameters as the base class storing the same information (in your case the message and Title) is repetition of data. Also a derived class variable hides the base class variable
of the same name ( which maybe what you want but it is something to be aware of)
Thanks for the help, I solved the problem
Topic archived. No new replies allowed.