dimanche 26 novembre 2017

How to define a derived class in c++?

I learnt Walter Savitch's Absolute C++ (5th ed.) about 2 years ago. The way to declare a derived class in this book is that

class ChildClass:Public ParentClass{...}

where the parent class is something like

class ParentClass
{Public:
 double getVariable() const;
...}

This book also says that if I do not want to change the definition of a member function of the parent class when I declare a derived class, I do not have to rewrite it in the derived class declaration. For example, if I do not want to change the definition of double ParentClass::getVariable() const, which assesses a member variable of ParentClass, I do not have to explicitly write it down again in the declaration of the derived class ChildClass.

Recently, I wanted to work out a project, and found something that changed over the years. Firstly, the declaration of the derived class should look like

class ChildClass:ParentClass{...}

You should not insert Public in front of ParentClass, otherwise, the compiler complains. Secondly, I cannot access the function double ParentClass::getVariable() const in the main program by the following code

childInstance.getVariable()

where childInstance is an instance of ChildClass.

These are the two things changing I found. Would you please tell me how to define a derived class in the correct way? Thank you!

By the way, the complier I am using is gcc 5.4.0 on Cygwin.

Aucun commentaire:

Enregistrer un commentaire