C++ Constructors Explained: Default and Parameterized Constructor
CODE:
#include<iostream>
using namespace std;
class Animal
{
public:
Animal()
{
cout<<"Animal Constructor called"<<endl;
}
};
class Human
{
public:
Human(string s)
{
cout<<"Human Constructor called : "<<s<<endl;
}
};
int main()
{
Animal A;
Human H("Wow");
return 0;
}
Explanation :
What is a Constructor? Constructor ka naam bilkul class ke naam jaisa hota hai aur iski koi return type (jaise int ya void) nahi hoti.
Default Constructor: Animal class mein koi value pass nahi karni parti. Jaise hi Animal A; likha, constructor chal gaya.
Parameterized Constructor: Human class mein humne aik string pass ki hai. Iska matlab hai ke object banate waqt hume value dena lazmi hai, jaise Human H("Wow");.
Automatic Execution: Humein in functions ko A.Animal() karke call nahi karna parta, ye khud hi execute ho jate hain.
Output:
Animal Constructor called
Human Constructor called : Wow
Post a Comment