Sunday, 2 June 2013

C++ Master Example

Following is the C++ master Program which contains examples for the following topics
// static
// this pointer
// constructor copy & parameterized
// destructor
// friend function
// inline function
// class and Objects
// call by reference
// overloading constructor
//default argument
You can write this example for any of the above theory.

class Person{

private:
int id;

public :
int age;
char fname[25];
char lname[25];
static int count;

// same name as class name
//no return type
// inittializes instance variables
// are called automatically when objects are created

Person(){
id=0;
age=0;
fname="";
lname="";
count++;
}

// default arguments
// parameterized constructor

Person(int a,int b=10,char c[],char d[]){
id=a;
age=b;
fname=c;
lname=d;
count++;
}

// copy constructor
Person(Person &p){
id=p.id;
age=p.age;
fname=p.fname;
lname=p.lname;
count++;
}
// destructor
~Person(){
cout << "Deleting Object "+count;
count--;
}

// conditions for function should be inline
// no static variable should be used
// loop or switch should not be there
// for fucntion not return values if return statement exists
// no recursion

inline int getAgeAfter10Years(){
return (age+10);
}

// can access private members of class
// generally has objects as arguments
// is not a member of a class
friend Person getPersonWithGreaterId(Person &p1,Person &p2);

// this pointer explanation
public Person greater(Person &p);
public static Person smaller(Person &p1,Person &p2);
}; // class ends

public Person Person::greater(Person &p){
if(age>p.age){
return *this;
}
else{
return p;
}
}

public static Person Person::smaller(Person &p1,Person &p2){
if(p1.age>p2.age){
return p2;
}
else{
return p1;
}
}
public Person getPersonWithGreaterId(Person &p1,Person &p2){
if(p1.id>p2.id){
return p1;
}
else{
return p2;
}
}


void main(){
Person p1,p2(1,20,"Mohan","Sharma"),p3(2,21,"Yatin","Makwana"),p4(3,22,"Pradip","Makwana");
Person p11(1,"Ronak","Kotak");
{
Person p5;
}
Person p6(p4);  //calling copy constructor
cout<<p6.fname;

Person p7=p3;  //calling copy constructor

cout<<p7.fname;

Person p8=p1.greater(p2);
cout<< p8.fname;
Person p9=Person.smaller(p2,p3);
cout<< p9.fname;
cout<< p9.getAgeAfter10Years();
Person p10=getPersonWithGreaterId(p3,p7);
cout<< p10.fname;
}

Output:

Deleting object 6
Pradip
Yatin
Mohan
Mohan
30
Yatin
Deleting Object 7
Deleting Object 6
Deleting Object 5
Deleting Object 4
Deleting Object 3
Deleting Object 2
Deleting Object 1

No comments:

Post a Comment