Skip to content

Commit baff4ca

Browse files
committed
Nested classes in cpp
1 parent 0a041d7 commit baff4ca

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

NestedClasses.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
//Nested classes-classes defined inside a class
5+
6+
7+
class Person {
8+
public:
9+
string name;
10+
11+
class Anish {
12+
public:
13+
string address;
14+
string city;
15+
string country;
16+
17+
18+
19+
20+
};
21+
//we need to define object of nested class to access its members inside Parent class
22+
23+
Anish a; //object created
24+
void getadd()
25+
{
26+
cout<<"Name: "<<name<<endl<<"Address:"<<a.address<<endl<<"City: "<<a.city<<endl<<"Country: "<<a.country<<endl;
27+
}
28+
29+
30+
31+
};
32+
33+
int main() {
34+
Person p;
35+
//creating object of nested clas outiside Parent class throws error
36+
//Person::Anish an; //need to use scope resolution operator
37+
p.a.address="Hari Kunj";
38+
p.a.city="Dehradun";
39+
p.a.country="India";
40+
p.name="Anish";
41+
p.getadd();
42+
return 0;
43+
44+
}

0 commit comments

Comments
 (0)