C++ tutorial-C++ classes inheritance

C++ Classes inheritance

To create inheritance, use the following syntax:

class derived_classname:access_level baseclass1, baseclase2,...{ }

access_level can be public, protected, or private.

To illustrate the use of inheritance, now we create a base class called Animal and a derived class called Dog.

using std::endl;

class Animal
     int numberOflegs;

     void setnumberOflegs(int n){numberOflegs = n;}
     int getnumberOflegs(){return numberOflegs;}

class Dog:public Animal{
       char *dogName;
      void setdogName(char *name){dogName = name;}
      char *getdogName(){return dogName;}

void main()
   Dog d;
   d.setnumberOflegs(4);//setnumberOflegs was inherited from the Animal class
   cout<<"Dog Name:"<<d.getdogName()<<endl;
   cout<<"Number of legs: "<<d.getnumberOflegs()<<endl;
  //getnumberOflegs was inherited from the Animal class

Note: Class members declared with public keyword has global access. Class members declared with protected keyword can only be access within their own class and derived class. Class members declared with private keyword can only be accessed in their own class.


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.