Constructor Example
Just open your c++ compiler Paste this code.
#include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count;
public:
Counter()
{
cout<<"Hello I am Constructor";
}
void inc_count() //increment count
{ count++; }
int get_count() //return count
{ return count; }
};
////////////////////////////////////////////////////////////////
int main()
{
Counter c1, c2;
cout << "\nc1="<< c1.get_count();
cout << "\nc2=" << c2.get_count();
c1.inc_count();
c2.inc_count();
c2.inc_count();
cout << "\nc1=" << c1.get_count(); //display again
cout << "\nc2=" << c2.get_count();
cout << endl;
return 0;
}
using namespace std;
class Counter
{
private:
unsigned int count;
public:
Counter()
{
cout<<"Hello I am Constructor";
}
void inc_count() //increment count
{ count++; }
int get_count() //return count
{ return count; }
};
////////////////////////////////////////////////////////////////
int main()
{
Counter c1, c2;
cout << "\nc1="<< c1.get_count();
cout << "\nc2=" << c2.get_count();
c1.inc_count();
c2.inc_count();
c2.inc_count();
cout << "\nc1=" << c1.get_count(); //display again
cout << "\nc2=" << c2.get_count();
cout << endl;
return 0;
}








0 comments: