Home » Code Snippets » C/C++ Code Snippets

C++ Class Exercise - Read and Print House details along with Room details.

In this C++ program we will learn how we can use one class’s object inside another class definition to read details of first class?

In this program we are creating three classes - room, address and house; room class will read the details of rooms, address class will read house address with city, state and house class will read house name.

In house class we are creating objects of room and address classes. Hence finally we will be able to read and print complete house details like address, name, room details etc.

C++ program - Read and Print House details along with Room details

Let’s consider the following example:

/*C++ Class Exercise - Read and Print House details 
along with Room details*/

#include<iostream>

using namespace std;

class room {
	int l;
	int b;
	int h;
	public : 
		void getroom()
		{
			cout<<"Enter length, breath, height: ";
			cin>>l>>b>>h;
		}
		void putroom()
		{
			cout<<"Length: "<<l<<",Breath: "<<b<<", Height: "<<h<<endl;
		}
};
class address {
	int hno;
	char cty[30];
	char state[30];
	public : 
		void getad()
		{
			cout<<"house number : ";
			cin>>hno;
			cout<<"city :";
			cin>>cty;
			cout<<"state : ";
			cin>>state;
		}
		void putad()
		{
			cout<<"House No.: "<<hno<<",city: "<<cty<<",state: "<<state<<endl;
		}
};

class house{
	char housename[30];
	address a;
	room r[10]; //max. 10 rooms

	public : 
			void input();
			void display();
};
//function definition
void house :: input()
{	
	cout<<"Enter house name: ";
	cin>>housename;
	cout<<"Enter Address : \n";
	a.getad();
	
	for(int i=0;i<3;i++){
		cout<<"House Details : "<<i+1<<"\n";
		r[i].getroom();
	}
}

//function definition
void house :: display()
{	
	cout<<"House name: "<<housename<<endl;
	cout<<"Address is: ";
	
	for(int i=0;i<3;i++){
		cout<<"House Details : "<<i+1<<"\n";
		r[i].putroom();
	}
}

int main()
{
	house x;
	x.input();
	x.display();
	return 0;
}

Output

    Enter house name: My_Sweet_Home 
    Enter Address : 
    house number : 101
    city :NY
    state : NY
    House Details : 1 
    Enter length, breath, height: 10 10 10
    House Details : 2 
    Enter length, breath, height: 10 10 8 
    House Details : 3 
    Enter length, breath, height: 20 20 10
    House name: My_Sweet_Home 
    Address is: House Details : 1 
    Length: 10,Breath: 10, Height: 10 
    House Details : 2 
    Length: 10,Breath: 10, Height: 8
    House Details : 3 
    Length: 20,Breath: 20, Height: 10 



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.