Home »
Code Snippets »
C/C++ Code Snippets
C++ Class Exercise - Read and Print Class, Students Details using Two Classes
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?
This program will read class details along with number of students in a class, so we will create student class first and then we will create classDetails class. Inside classDetails class we will use object of student class’s object.
C++ program - Read and print Class, Student details using Two Classes
Let’s consider the following example:
/*C++ Class Exercise - Read and Print Class, Students
Details using Two Classes*/
#include <iostream>
#include <string.h>
using namespace std;
class student{
private:
char name[30];
int rollNo;
public:
void getStudent(){
strcpy(name,"PIYA KAUSHAL");
rollNo=101;
}
void printStudent(){
cout<<"Name: "<<name<<",Roll No.: "<<rollNo<<endl;
}
};
class classDetails{
private:
char clsName[30];
student std; //object
public:
void getClassDetails(){
strcpy(clsName,"Higher Sec.");
std.getStudent();
}
void printClassDetails(){
cout<<"Class Name: "<<clsName<<endl;
std.printStudent();
}
};
int main()
{
classDetails CD;
CD.getClassDetails();
CD.printClassDetails();
return 0;
}
Output
Class Name: Higher Sec.
Name: PIYA KAUSHAL,Roll No.: 101