Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 15

Programming in C++

1. Write a simple C++ program.


2. Write a program for copy constructor.
3. Write a program for destructor.
4. Write a program for friend function.
5. Write a program for this pointer.
6. Write a program for call by value and
call by reference
7. What are Virtual Functions? How to
implement virtual functions in “C++”
8. Write a program for operator
overloading.
9. Write a program for function overriding.
10. Write a program for multiple
inheritances.
1. Write a simple C++ program.

The Car Rental company charges Rs. 0.25/mile if the total mileage does not exceed 100. If the total
mileage is over 100, the company charges Rs0.25/mile for the first 100 miles, then it charges Rs0.15/mile
for any additional mileage over 100.
Than we will have following program

#include <iostream>

void main()
{
unsigned int Miles;
const double LessThan100 = 0.25;
const double MoreThan100 = 0.15;
double PriceLessThan100, PriceMoreThan100, TotalPrice;

cout << "Enter the number of miles: ";


cin >> Miles;

if(Miles <= 100)


{
PriceLessThan100 = Miles * LessThan100;
PriceMoreThan100 = 0;
}
else
{
PriceLessThan100 = 100 * LessThan100;
PriceMoreThan100 = (Miles - 100) * MoreThan100;
}

TotalPrice = PriceLessThan100 + PriceMoreThan100;

cout << "\nTotal Price = Rs" << TotalPrice << "\n\n";


}

2. Write a program for copy constructor.

#include <iostream>

#include <string>

struct SomeData

{   int * pd;   

string id;   
SomeData(SomeData & ref)

{     cout << "Copy Constructor called" << endl;     pd = new int (*ref.pd) ;     id = "Copy Constructed";   }

SomeData(string name)

{     pd = new int(0) ;     id=name;     cout << "Constructor for " << id << endl;   };   

~SomeData()

{     cout << "Destructor for " << id << endl;     delete pd;   } };

int main()

{   SomeData s("First") ;   *s.pd =9;   SomeData s2=s;   cout << *s2.pd << endl;   return 0; }

3. Write a program for destructor.

#include <string>

class Y { private: char * string;

int number;

public:

// Constructor

Y(const char*, int);

// Destructor

~Y() { delete[] string; }

};

// Define class Y constructor

Y::Y(const char* n, int a) {

string = strcpy(new char[strlen(n) + 1 ], n);

number = a;

int main () {

// Create and initialize

// object of class Y

Y yobj = Y("somestring", 10);


// Destructor ~Y is called before

// control returns from main()

4. Write a program for friend function.

/* C++ program for the Implementation Of Friend Function */

#include< iostream.h>
#include< conio.h>
class complex
{
float real;
float imag;
public:
void getdata(float x,float y)
{
real=x;
imag=y;
}
friend complex add (complex c1,complex c2);
void display()
{
cout< < "the complex no is"< < real< < "+i"< < imag< < endl;
}

};
complex add (complex c1,complex c2)
{
complex c3;
c3.real=c1.real+c2.real;
c3.imag=c1.imag+c2.imag;
return (c3);

}
void main()
{
clrscr();
complex c1,c2,c3;

c1.getdata(4.2,5.5);
c2.getdata(3.5,5.6);
c3=add(c1,c2);
c3.display();
}
5. Write a program for this pointer.

// Using the this pointer

#include <iostream.h>

class Rectangle

{ public:

Rectangle();

~Rectangle();

void SetLength(int length) { this->itsLength = length; }

int GetLength() const { return this->itsLength; }

void SetWidth(int width) { itsWidth = width; }

int GetWidth() const { return itsWidth; }

private:

int itsLength;

int itsWidth;

};

Rectangle::Rectangle()

{ itsWidth = 5; itsLength = 10; }

Rectangle::~Rectangle() {}

int main()

{ Rectangle theRect;

cout << "theRect is " << theRect.GetLength() << " feet long.\n";

cout << "theRect is " << theRect.GetWidth() << " feet wide.\n";

theRect.SetLength(20);

theRect.SetWidth(10);

cout << "theRect is " << theRect.GetLength()<< " feet long.\n";

cout << "theRect is " << theRect.GetWidth()<< " feet wide.\n";

return 0; }
Output: theRect is 10 feet long.

theRect is 5 feet wide.

theRect is 20 feet long.

6. Write a program for call by value and call by reference

void by_value(int a){


a+=10;
}

void by_ref(int *a){


(*a)+=10;
}

void by_ref2(int &a){


a+=10;
}

int main(){
int x=40;
by_value(x);
//x==40
by_ref(&x);
//x==50
by_ref2(x);
//x==60
return 0;
}

7. What are Virtual Functions? How to implement virtual functions in “C++”

In object-oriented programming, a virtual function or virtual method is a function or method whose


behaviour can be overridden within an inheriting class by a function with the same signature. This concept
is a very important part of the polymorphism portion of object-oriented programming (OOP).

class classname //This denotes the base class of C++ virtual function
{ public:
virtual void memberfunctionname() //This denotes the C++ virtual function
{
............
}
};

class Vehicle //This denotes the base class of C++ virtual function
{ public:
virtual void Make() //This denotes the C++ virtual function
{
cout <<"Member function of Base Class Vehicle Accessed"<<endl;
} };

class Vehicle   //This denotes the base class of C++ virtual function
{ public:
virtual void Make()   //This denotes the C++ virtual function
{
cout <<"Member function of Base Class Vehicle Accessed"<<endl;
} };

class FourWheeler : public Vehicle


{ public:
void Make()
{
cout<<"Virtual Member function of Derived class FourWheeler Accessed"<<endl;
} };

void main()
{
Vehicle *a, *b;
a = new Vehicle();
a->Make();
b = new FourWheeler();
b->Make(); }

8. Write a program for operator overloading.

#include <iostream.h>
/* Demonstration of operator overloading in C++ */
class Cube {
        public:
                Cube::Cube(float inx, float iny, float inz);
                Cube operator+ (const Cube &);
                float Cube::getX();
                float Cube::getY();
                float Cube::getZ();
                void Cube::report(char *descr);
        private:
                float x;
                float y;
                float z;};

Cube::Cube(float inx, float iny, float inz) {
        x = inx; y = iny; z = inz;
        }
Cube Cube::operator+ (const Cube & second) {
        float newx = (x > second.x) ? x : second.x;
        float newy = (y > second.y) ? y : second.y;
        float newz = z + second.z;
        return Cube(newx,newy,newz);
        }
float Cube::getX () {
        return x;
        }
float Cube::getY () {
        return y;
        }
float Cube::getZ () {
        return z;
        }

void Cube::report(char *descr) {
        cout << descr << " "
                << this->getX()
                << " by " << this->getY()
                << " by " << this->getZ()
                << endl;
        }
int main () {
        Cube Compaq = Cube(33.0,17.0,3.0);
        Cube Powerbook = Cube(39.0,16.0,1.8);
        Cube Combo = Compaq + Powerbook;

        Compaq.report("Compaq Evo N1050v");
        Powerbook.report("17\" Powerbook G4");
        Combo.report("Both computers together");}

9. Write a program for function overriding.

void AddAndDisplay(int x, int y)


    {
        cout<<" C++ Tutorial - Integer result: "<<(x+y);
    }

    void AddAndDisplay(double x, double y)


    {
        cout<< " C++ Tutorial - Double result: "<<(x+y);
    }

    void AddAndDisplay(float x, float y)


    {
        cout<< " C++ Tutorial - float result: "<<(x+y);

    }

Some times when these overloaded functions are called, they might cause
ambiguity errors. This is because the compiler may not be able to decide what
signature function should be called.

10. Write a program for multiple inheritances.


#include <iostream.h>
class Horse
{
public:
Horse() { cout << "Horse constructor... "; }
virtual ~Horse() { cout << "Horse destructor... "; }
virtual void Whinny() const { cout << "Whinny!... "; }
private:
int itsAge;
};
class Bird
{ public:
Bird() { cout << "Bird constructor... "; }
virtual ~Bird() { cout << "Bird destructor... "; }
virtual void Chirp() const { cout << "Chirp... "; }
virtual void Fly() const
{ cout << "I can fly! I can fly! I can fly! ";
}
private:
int itsWeight;
};
class Pegasus : public Horse, public Bird
{ public:
void Chirp() const { Whinny(); }
Pegasus() { cout << "Pegasus constructor... "; }
~Pegasus() { cout << "Pegasus destructor... "; }
};
const int MagicNumber = 2;
int main()
{ Horse* Ranch[MagicNumber];
Bird* Aviary[MagicNumber];
Horse * pHorse;
Bird * pBird;
int choice,i;
for (i=0; i<MagicNumber; i++)
{ cout << "\n(1)Horse (2)Pegasus: ";
cin >> choice;
if (choice == 2)
pHorse = new Pegasus;
else
pHorse = new Horse;
Ranch[i] = pHorse;
}
for (i=0; i<MagicNumber; i++)
{
cout << "\n(1)Bird (2)Pegasus: ";
cin >> choice;
if (choice == 2)
pBird = new Pegasus;
else
pBird = new Bird;
Aviary[i] = pBird;
}
cout << "\n";
for (i=0; i<MagicNumber; i++)
{ cout << "\nRanch[" << i << "]: " ;
Ranch[i]->Whinny();
delete Ranch[i];
}
for (i=0; i<MagicNumber; i++)
{ cout << "\nAviary[" << i << "]: " ;
Aviary[i]->Chirp();
Aviary[i]->Fly();
delete Aviary[i];
} return 0; }
11. Write a program for this pointer.

Every class member function has a hidden parameter: the this pointer. this points to the individual
object. Therefore, in each call to GetAge() or SetAge(), the this pointer for the object is included
as a hidden parameter.

It is possible to use the this pointer explicitly, as program below illustrates.

Using the this pointer

//
// Using the this pointer

#include <iostream.h>

class Rectangle
{
public:
Rectangle();
~Rectangle();
void SetLength(int length) { this->itsLength = length; }
int GetLength() const { return this->itsLength; }

void SetWidth(int width) { itsWidth = width; }


int GetWidth() const { return itsWidth; }

private:
int itsLength;
int itsWidth;
};
Rectangle::Rectangle()
{
itsWidth = 5;
itsLength = 10;
}
Rectangle::~Rectangle()
{}

int main()
{
Rectangle theRect;
cout << "theRect is " << theRect.GetLength() << " feet long.\n";
cout << "theRect is " << theRect.GetWidth() << " feet wide.\n";
theRect.SetLength(20);
theRect.SetWidth(10);
cout << "theRect is " << theRect.GetLength()<< " feet long.\n";
cout << "theRect is " << theRect.GetWidth()<< " feet wide.\n";
return 0;
}

Output: theRect is 10 feet long.


theRect is 5 feet wide.
theRect is 20 feet long.
theRect is 10 feet wide.

Analysis: The SetLength() and GetLength() accessor functions explicitly use the this pointer
to access the member variables of the Rectangle object. The SetWidth and GetWidth accessors
do not. There is no difference in their behavior, although the syntax is easier to understand.
If that were all there was to the this pointer, there would be little point in bothering you with it. The
this pointer, however, is a pointer; it stores the memory address of an object. As such, it can be a
powerful tool.

You don't have to worry about creating or deleting the this pointer. The compiler takes care of that.
What are Virtual Functions?

Virtual, as the name implies, is something that exists in effect but not in reality. The concept of virtual
function is the same as a function, but it does not really exist although it appears in needed places in
a program. The object-oriented programming language C++ implements the concept of virtual
function as a simple member function, like all member functions of the class.

The functionality of virtual functions can be over-ridden in its derived classes. The programmer must
pay attention not to confuse this concept with function overloading. Function overloading is a different
concept and will be explained in later sections of this tutorial. Virtual function is a mechanism to
implement the concept of polymorphism (the ability to give different meanings to one function).

Need for Virtual Function:

The vital reason for having a virtual function is to implement a different functionality in the derived
class.

For example: a Make function in a class Vehicle may have to make a Vehicle with red color. A class
called FourWheeler, derived or inherited from Vehicle, may have to use a blue background and 4 tires
as wheels. For this scenario, the Make function for FourWheeler should now have a different
functionality from the one at the class called Vehicle. This concept is called Virtual Function.

Properties of Virtual Functions:


 Dynamic Binding Property:

Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also simple
member functions. The main difference between a non-virtual C++ member function and a virtual
member function is in the way they are both resolved. A non-virtual C++ member function is resolved
during compile time or static binding. Virtual Functions are resolved during run-time or dynamic
binding

 Virtual functions are member functions of a class.

 Virtual functions are declared with the keyword virtual, detailed in an


example below.

 Virtual function takes a different functionality in the derived class.

Declaration of Virtual Function:

Virtual functions are member functions declared with the keyword virtual.
For example, the general syntax to declare a Virtual Function uses:

class classname //This denotes the base class of C++ virtual function
{
public:
virtual void memberfunctionname() //This denotes the C++ virtual function
{
.............
............
}
};

Referring back to the Vehicle example, the declaration of Virtual function would take the shape below:
class Vehicle //This denotes the base class of C++ virtual function
{
public:
virtual void Make() //This denotes the C++ virtual function
{
cout <<"Member function of Base Class Vehicle Accessed"<<endl;
}
};

After the virtual function is declared, the derived class is defined. In this derived class, the new
definition of the virtual function takes place.

When the class FourWheeler is derived or inherited from Vehicle and defined by the virtual function in
the class FourWheeler, it is written as:

class Vehicle   //This denotes the base class of C++ virtual function
{
public:
virtual void Make()   //This denotes the C++ virtual function
{
cout <<"Member function of Base Class Vehicle
Accessed"<<endl;
}
};

class FourWheeler : public Vehicle


{
public:
void Make()
{
cout<<"Virtual Member function of Derived class
FourWheeler Accessed"<<endl;
}
};
void main()
{
Vehicle *a, *b;
a = new Vehicle();
a->Make();
b = new FourWheeler();
b->Make();
}

In the above example, it is evidenced that after declaring the member functions Make() as virtual
inside the base class Vehicle, class FourWheeler is derived from the base class Vehicle. In this derived
class, the new implementation for virtual function Make() is placed. The programmer might be
surprised to see the function call differs and the output is then printed as above. If the member
function has not been declared as virtual, the base class member function is always called because
linking takes place during compile time and is therefore static. In this example, the member function
is declared virtual and the address is bounded only during run time, making it dynamic binding and
thus the derived class member function is called. To achieve the concept of dynamic binding in C++,
the compiler creates a v-table each time a virtual function is declared. This v-table contains classes
and pointers to the functions from each of the objects of the derived class. This is used by the
compiler whenever a virtual function is neede

You might also like