Home » C++ programs » C++ Class and Objects programs

Create an object of a class inside another class declaration in C++

Here, we are going to learn by a program how to create an object of a class inside another class declaration in C++ programming language?
Submitted by IncludeHelp, on September 15, 2018

As we know that a class contains data members and member function, and an object can also be a data member for another class.

Here, in the given program, we are doing the same. We have a class named Marks that contains two data members rno - to store roll number and perc - to store the percentage of the student. We have another class named Students that contains two members name - to store the name of the student and objM - which is an object of Marks class.

In Students class there are two member functions:

  1. readStudent() - To read the name of the student, and Here, we called readMarks() member function of Marks class by using objM - it will read roll number and percentage.
  2. printStudent() - To print the name of the student, and Here, we called printMarks() member function of Marks class by using objM - it will print roll number and percentage.

Program:

#include <iostream>
#include <string.h>

using namespace std;

class Marks
{
	private:
		int rno;
		float perc;
	
	public:
		//constructor
		Marks()
		{rno = 0; perc = 0.0f;}
		
		//input roll numbers and percentage
		void readMarks(void)
		{
			cout<<"Enter roll number: ";
			cin>>rno;
			cout<<"Enter percentage: ";
			cin>>perc;
		}
		
		//print roll number and percentage
		void printMarks(void)
		{
			cout<<"Roll No.: "<<rno<<endl;
			cout<<"Percentage: "<<perc<<"%"<<endl;
		}
};

class Student
{
	private:
		//object to Marks class
		Marks objM;
		char name[30];
	
	public:
		//input student details
		void readStudent(void)
		{
			//Input name
			cout<<"Enter name: ";
			cin.getline(name, 30);
			//input Marks
			objM.readMarks();			
		}
		
		//print student details
		void printStudent(void)
		{
			//print name
			cout<<"Name: "<<name<<endl;
			//print marks
			objM.printMarks();
		}
};

//main code
int main()
{
	//create object to student class
	Student std;
	std.readStudent();
	std.printStudent();
	
	return 0;
}

Output

Enter name: Amit Shukla
Enter roll number: 101
Enter percentage: 84.02
Name: Amit Shukla
Roll No.: 101
Percentage: 84.02%




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.