C++: Inheritance|Container class

Container class

When a class contains objects of another class as its data elements then such a class is termed as a container class.

Syntax:

class A
{
};
class B
{
};
class C
{
A a1;
B b1;
};

Then class “C” is called as container class as it contains objects of classes “A” and “B” as its data elements.

Example:

Declare a class named student with attributes as roll and name. declare another class named physical with attributes as age, height and weight. Declare another class named marks with attributes as object of student,object of physical, marks of three subjects , total and per. Take input for the details and display them.

 

//container class
#include<iostream>
#include<conio.h>
using namespace std;
class student
{
private:
	int roll;
	char name[20];
public:
	void read();
	void show();
};
class physical
{
private:
	float age,ht,wt;
public:
	void read();
	void show();
};
//class marks is container class as it
//contains objects  of classes student and physical
//as its data elements.
class marks
{
private:
	student s;
	physical p;
	float m1,m2,m3,total,per;
public:
	void read();
	void show();
};
void student::read()
{
  cout<<"Enter roll and name ";
  cin>>roll>>name;
}
void student::show()
{
  cout<<"roll "<<roll<<" name "<<name<<endl;
}
void physical::read()
{
  cout<<"Enter age ,height and weight ";
  cin>>age>>ht>>wt;
}
void physical::show()
{
  cout<<"age "<<age<<" Height "<<ht<<" weight "<<wt<<endl;
}
void marks::read()
{
  s.read();
  p.read();
  cout<<"Enter marks of m1,m2 and m3 ";
  cin>>m1>>m2>>m3;
}
void marks::show()
{
  s.show();
  p.show();
  total=m1+m2+m3;
  per=total/3;
  cout<<"total "<<total<<" per "<<per<<endl;
}
int main()
{
  marks m;
  m.read();  m.show();
  return(0);
}

Output:

Enter roll and name 101
abc
Enter age ,height and weight 2
3
6
Enter marks of m1,m2 and m3 98
97
95
roll 101 name abc
age 2 Height 3 weight 6
total 290 per 96.6667