Detailed Print – CSKC
Sign In

Search

siteicon
Code Learning#CPP#4673 Back

Child class reading parent class data member

Understanding how a child class object read the parent class data member easily.

Learning Objectives

  • Learning how child class can read parent class data member once it is inherited with public accessiblity.

Source Code

		 

Click to open popup

Run Output

No. of Walls = 4
Bed in Room = 1

Code Understanding

class Room
{
public:
int walls;
Room(){walls=4;}
};
This class is parent class and it defines a data member walls that is initialised with value 4 using a constructor.

class BedRoom:public Room
{
public:
int beds;
BedRoom(){beds=1;}
};
This class is child class inherited from class Room and it defines a data member beds that is initialised with value 1 using a constructor.

int main() {
BedRoom b;
Here we are defining the object of child class only.

cout<<“No. of Walls = “<<b.walls<<endl;
Here we are printing the member of parent class using the data member of parent class. This is possible due to inheritance only.

cout<<“Bed in Room = “<<b.beds<<endl;
Here we are printing the member of child class itself using its own data member which is possible as it is a public member.

return 0;}

Notes

  • public accessibility is important while inheriting the child class in this type of code. Other accessibility may pose certain limits.


Suggested Filename(s): smpl-inh.cpp,simple-inheritance.cpp,child-reading-parent.cpp