Nested classes
Like nested if(), classes can also be nested. That is we can declare one class into another class.
The class that is declared in another class is called an inner class while the outer class in which
we are declaring the inner class is called as Enclosing class.
Syntax :
class outer-class-name
{
private:
data member;
member function;
public:
data member;
member function;
class inner-class-name
{
private:
data member;
member function;
public:
data member;
member function;
};
};
class outer-class-name obj1;
class outer-class-name :: inner-class-name obj2;
Example :
#include <iostream.h>
#include <conio.h>
class Account
{
private:
int accountno;
public:
void setRecord();
void display();
class Time //start of inner class
{
private :
int hour;
int min;
int sec;
public:
void setTime(int h,int m,int s);
void displayTime();
}; //end of inner class
}; //end of outer class
void Account :: setRecord()
{
cout<<"Enter the account no : ";
cin>>accountno;
}
void Account :: display()
{
cout<<"\n\nAccount no is : " << accountno;
}
void Account :: Time :: setTime(int h,int m,int s)
{
hour=h;
min=m;
sec=s;
}
void Account :: Time :: displayTime()
{
cout << "\n\nCreation Time is : " ;
cout << hour<<":"<< min<< ":" << sec;
}
void main()
{
clrscr();
Account acc;
//creating object of inner class
Account :: Time time;
acc.setRecord();
time.setTime(10,30,50);
acc.display();
time.displayTime();
getch();
}
Output :
Prev NEXT
0 comments:
Post a Comment