Friday, February 22, 2013

OOCP (CPP) : Example # 08 : Constructor Example using c++

OOCP (CPP)  :  Example # 08 : Constructor Example using c++

* Lets start learning CPP (C++) Using Example.
* Constructor Example using c++.

//Written by Latest Technology Guide    
//Title : OOCP (CPP)  :  Example # 
08 : Constructor Example using c++

/*
Our own Constructor

Characteristics of Constructor
- No Return Value (not even void)
- Name of Const and Name of Class must be Same

Note :-
Constance Value assign from right to left while Parameter value assign from left to right
*/

#include <iostream.h>
#include <iomanip.h>
#include <conio.h>

class Value
{
private:
int a;
float b;
char *info;
public :
Value(); //Constructor with No para
Value(int,float,char*); //Constructor with 3 para
void display();
};
//====================================================
// Constructor with Parameter
//====================================================
Value :: Value(int m, float n=300.0,char *ptr="Ram")
{
cout << "Constructor is called with Parameter" << endl;
a = m;
b = n;
info = ptr;
}

//====================================================
// Constructor without Parameter
//====================================================
Value :: Value()
{
cout << "Constructor is called without Parameter" << endl;
a = 0;
b = 0.0;
info = " ";
}

//====================================================
// Display Function
//====================================================
void Value :: display()
{
cout << "Integer Value is : "     << a << endl;
cout << "Float   Value is : " << b << endl;
cout << "String  Value is : " << info << endl;
}
//=================================================
// Main Function
//=================================================
void main()
{
clrscr();
char *str="This is my Name";

Value obj1;
obj1.display();

Value obj2(10,100.80,str);
obj2.display();

Value obj3(20,200.67,"Bhav Uni");
obj3.display();

Value obj4(30);
obj4.display();

getch();
}

Output:
* CPP Constructor Example.

--------------------------------------------------------------------------------
OOCP (CPP)  :  Example # 08 : Constructor Example using c++

* Example demonstrate how to work with Constructor.


Note: All programs are developed and tested using Turbo C++ 3.0 under Windows XP. We just want to provide guidelines to the users. If you are using any other Compiler or other operating system they you need to modify this program as per your requirements. 

1 comment: