Skip to content

Commit 070c00d

Browse files
committed
constructors in cpp
1 parent 96448c7 commit 070c00d

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

OOP-2.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include<iostream>
2+
3+
using namespace std;
4+
5+
class human{
6+
7+
public:
8+
9+
string name;
10+
void introduce();
11+
12+
13+
};
14+
15+
16+
//scope resolution operator-used to define the class methods outside the class
17+
void human :: introduce()
18+
{
19+
cout<<"Hello"<<" " <<human :: name <<endl;
20+
}
21+
22+
23+
int main ()
24+
{
25+
human obj1;
26+
obj1.name="Anish";
27+
obj1.introduce();
28+
29+
human *obj2 = new human; //pointer method of creating an dynamic object stored in HEAP section of memory
30+
obj2->name="Mrinal";
31+
obj2->introduce();
32+
cout<<obj2; //displays the address of memory in heap
33+
34+
return 0;
35+
}

constructors.cpp

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//constructors example
2+
#include<iostream>
3+
4+
using namespace std;
5+
6+
7+
class human
8+
{
9+
public:
10+
human() {
11+
int age=10;
12+
string name="Anish";
13+
cout<<"Constructor is called"<<endl;
14+
}
15+
16+
void introduce()
17+
{
18+
cout<<"Hello I am" <<" " << getName() << " "<<"and my age is" << getage()<<endl;
19+
}
20+
21+
int getage()
22+
{
23+
cin>>age;
24+
return age;
25+
26+
}
27+
string getName()
28+
{
29+
30+
cin>>name;
31+
return name;
32+
33+
}
34+
35+
private:
36+
int age;
37+
string name;
38+
39+
40+
};
41+
42+
43+
int main() {
44+
human *obj= new human;//constructor is called as soon as an object is created
45+
obj->introduce();
46+
}

constructors.exe

2.59 MB
Binary file not shown.

0 commit comments

Comments
 (0)