P. 1
c++Practical

c++Practical

|Views: 6|Likes:
Published by Shailendra Yadav

More info:

Published by: Shailendra Yadav on May 20, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

05/20/2011

pdf

text

original

Programming in C

++

1. 2. 3. 4. 5.

Write a simple C++ program.

Write a program for copy constructor. Write a program for destructor. Write a program for friend function. 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.

const double MoreThan100 = 0.pd) . = (Miles . double PriceLessThan100. If the total mileage is over 100. if(Miles <= 100) { PriceLessThan100 PriceMoreThan100 } else { PriceLessThan100 PriceMoreThan100 } = Miles * LessThan100. } SomeData(string name) { pd = new int(0) . TotalPrice. The Car Rental company charges Rs. PriceMoreThan100. = 0. SomeData(SomeData & ref) { cout << "Copy Constructor called" << endl. = 100 * LessThan100. cout << "Enter the number of miles: ". Write a program for copy constructor.15. then it charges Rs0. cin >> Miles. (*ref. id=name. Write a simple C++ program.25/mile for the first 100 miles. the company charges Rs0. Than we will have following program #include <iostream> void main() { unsigned int Miles. string id.25/mile if the total mileage does not exceed 100. const double LessThan100 = 0.15/mile for any additional mileage over 100. }.1.25. #include <iostream> #include <string> struct SomeData { int * pd. id = "Copy Constructed". cout << "Constructor for " << pd = new int .100) * MoreThan100. } cout << "\nTotal Price = Rs" << TotalPrice << "\n\n". id << endl. 2. TotalPrice = PriceLessThan100 + PriceMoreThan100. 0.

SomeData s2=s. number = a. cout << *s2. . Write a program for destructor. 4. } }. return 0. // Define class Y constructor Y::Y(const char* n.pd 3. #include <string> class Y { private: int number. int). public: // Constructor Y(const char*. int main() { SomeData s("First") . } }. } int main () { // Create and initialize // object of class Y Y yobj = Y("somestring". // Destructor ~Y is called before // control returns from main() ] char * string. // Destructor ~Y() { delete[] string. } *s. n). 10).pd =9. Write a program for friend function. int a) { string = strcpy(new char[strlen(n) + 1 ]. << endl.~SomeData() { cout << "Destructor for " << id << endl. delete pd.

imag=y. c3=add(c1. c2.real.imag. // Using the this pointer #include <iostream. c3.5.2. return (c3). } 5.getdata(3.complex c2) { complex c3. void display() { cout< < "the complex no is"< < real< < "+i"< < imag< < endl. } void main() { clrscr().real+c2./* C++ program for the Implementation Of Friend Function */ #include< iostream.c2.complex c2).display(). c1. public: void getdata(float x.5.float y) { real=x. complex c1. float imag. Write a program for this pointer. c3.5.6).h> #include< conio.imag+c2.c3.5).real=c1. complex add (complex c1.h> class complex { float real.imag=c1. c3. } friend complex add (complex c1.getdata(4. } }.h> class Rectangle { public: .c2).

. } void SetWidth(int width) { itsWidth = width. theRect. } private: int itsLength.Rectangle(). } Output: theRect is 10 feet long. } int GetLength() const { return this->itsLength. }. theRect.GetWidth()<< " feet wide. return 0. theRect is 5 feet wide. cout << "theRect is " << theRect. cout << "theRect is " << theRect. cout << "theRect is " << theRect.SetWidth(10).GetWidth() << " feet wide.\n". 6. int itsWidth. } int GetWidth() const { return itsWidth. Write a program for call by value and call by reference void by_value(int a){ a+=10. ~Rectangle(). Rectangle::Rectangle() { itsWidth = 5. theRect is 20 feet long. {} } Rectangle::~Rectangle() int main() { Rectangle theRect.\n". itsLength = 10.\n".\n". cout << "theRect is " << theRect.GetLength() << " feet long. void SetLength(int length) { this->itsLength = length.GetLength()<< " feet long.SetLength(20).

class FourWheeler : public Vehicle { public: void Make() .. What are Virtual Functions? How to implement virtual functions in “C++” In object-oriented programming. //x==50 by_ref2(x).} void by_ref(int *a){ (*a)+=10. } }. 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.. 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). //x==40 by_ref(&x). } }.... by_value(x).... class classname //This denotes the base class of C++ virtual function { public: virtual void memberfunctionname() //This denotes the C++ virtual function { ... } 7.. //x==60 return 0. } int main(){ int x=40. } }. } void by_ref2(int &a){ a+=10. 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.

float y. float newy = (y > second. a->Make(). b->Make(). } Cube Cube::operator+ (const Cube & second) { float newx = (x > second. float Cube::getY().y) ? y : second.}. Write a program for operator overloading. #include <iostream. float iny. float Cube::getX(). } float Cube::getY () { return y. b = new FourWheeler(). void Cube::report(char *descr).y. float inz). *b.newy. Cube operator+ (const Cube &).{ cout<<"Virtual Member function of Derived class FourWheeler Accessed"<<endl. } float Cube::getX () { return x. a = new Vehicle().z.h> /* Demonstration of operator overloading in C++ */ class Cube { public: Cube::Cube(float inx. } }. float iny. z = inz. } 8. } float Cube::getZ () { return z.x. return Cube(newx. } void Cube::report(char *descr) { . void main() { Vehicle *a. float Cube::getZ(). float newz = z + second. float z. private: float x. y = iny. float inz) { x = inx.newz).x) ? x : second. Cube::Cube(float inx.

This is because the compiler may not be able to decide what signature function should be called.3. } void AddAndDisplay(double x.report("17\" Powerbook G4"). Cube Combo = Compaq + Powerbook. } int main () { Cube Compaq = Cube(33. } Some times when these overloaded functions are called.17.h> class Horse { public: .report("Both computers together"). } void AddAndDisplay(float x. Compaq.Integer result: "<<(x+y). 10.1. #include <iostream.Double result: "<<(x+y). double y) { cout<< " C++ Tutorial . int y) { cout<<" C++ Tutorial .cout << descr << " " << this->getX() << " by " << this->getY() << " by " << this->getZ() << endl. Cube Powerbook = Cube(39. Powerbook. Write a program for multiple inheritances.0.16. void AddAndDisplay(int x.float result: "<<(x+y). Write a program for function overriding. Combo.report("Compaq Evo N1050v").0.0). float y) { cout<< " C++ Tutorial .0.0.8).} 9. they might cause ambiguity errors.

.... } virtual ~Horse() { cout << "Horse destructor... i++) { cout << "\n(1)Horse (2)Pegasus: ". ". if (choice == 2) pHorse = new Pegasus. for (i=0. public Bird { public: void Chirp() const { Whinny(). } cout << "I can fly! I can fly! I can fly! ". int main() { Horse* Ranch[MagicNumber].Horse() { cout << "Horse constructor. Bird * pBird. const int MagicNumber = 2. else ". Bird* Aviary[MagicNumber]. }. } ~Pegasus() { cout << "Pegasus destructor. int choice... class Pegasus : public Horse. virtual void Fly() const { } private: int itsWeight.. }. cin >> choice... } private: int itsAge. "... } virtual void Chirp() const { cout << "Chirp.. ". i<MagicNumber. ".. ". }.i. Horse * pHorse. } . class Bird { public: Bird() { cout << "Bird constructor. } virtual ~Bird() { cout << "Bird destructor.. ". ". } virtual void Whinny() const { cout << "Whinny!. } Pegasus() { cout << "Pegasus constructor.

} for (i=0. } return 0. i<MagicNumber. Aviary[i] = pBird. i++) { cout << "\n(1)Bird (2)Pegasus: ". if (choice == 2) pBird = new Pegasus. delete Aviary[i]. else pBird = new Bird. i++) { cout << "\nAviary[" << i << "]: " . i<MagicNumber. } cout << "\n". for (i=0. } .pHorse = new Horse. Aviary[i]->Chirp(). } for (i=0. Ranch[i] = pHorse. Ranch[i]->Whinny(). delete Ranch[i]. cin >> choice. i<MagicNumber. i++) { cout << "\nRanch[" << i << "]: " . Aviary[i]->Fly().

~Rectangle(). this points to the individual object. Using the this pointer // // Using the this pointer #include <iostream. void SetLength(int length) { this->itsLength = length. } int GetLength() const { return this->itsLength.11. the this pointer for the object is included as a hidden parameter. } int GetWidth() const { return itsWidth. in each call to GetAge() or SetAge(). as program below illustrates. } private: . It is possible to use the this pointer explicitly. } void SetWidth(int width) { itsWidth = width. Therefore. Write a program for this pointer.h> class Rectangle { public: Rectangle(). Every class member function has a hidden parameter: the this pointer.

theRect is 10 feet wide. Rectangle::Rectangle() { itsWidth = 5.GetWidth() << " feet wide. Analysis: The SetLength() and GetLength() accessor functions explicitly use the this pointer to access the member variables of the Rectangle object.\n". itsLength = 10. . theRect.\n". If that were all there was to the this pointer. return 0. The this pointer. theRect. is a pointer.SetWidth(10). As such. You don't have to worry about creating or deleting the this pointer.GetLength() << " feet long.int itsLength. theRect is 5 feet wide. } Rectangle::~Rectangle() {} int main() { Rectangle theRect. cout << "theRect is " << theRect. theRect is 20 feet long. it can be a powerful tool. there would be little point in bothering you with it.SetLength(20). The compiler takes care of that. The SetWidth and GetWidth accessors do not. it stores the memory address of an object. int itsWidth. cout << "theRect is " << theRect.GetWidth()<< " feet wide. } Output: theRect is 10 feet long.\n". cout << "theRect is " << theRect. There is no difference in their behavior. however. cout << "theRect is " << theRect.GetLength()<< " feet long. }. although the syntax is easier to understand.\n".

Need for Virtual Function: The vital reason for having a virtual function is to implement a different functionality in the derived class. is something that exists in effect but not in reality. the Make function for FourWheeler should now have a different functionality from the one at the class called Vehicle. but it does not really exist although it appears in needed places in a program. derived or inherited from Vehicle. The functionality of virtual functions can be over-ridden in its derived classes. This concept is called Virtual Function. The concept of virtual function is the same as a function. For this scenario. Virtual function is a mechanism to implement the concept of polymorphism (the ability to give different meanings to one function). The object-oriented programming language C++ implements the concept of virtual function as a simple member function. For example: a Make function in a class Vehicle may have to make a Vehicle with red color. as the name implies.What are Virtual Functions? Virtual. like all member functions of the class. A class called FourWheeler. Properties of Virtual Functions:  Dynamic Binding Property: . 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. may have to use a blue background and 4 tires as wheels.

the derived class is defined. Virtual functions are declared with the keyword virtual.Virtual Functions are resolved during run-time or dynamic binding.. Declaration of Virtual Function: Virtual functions are member functions declared with the keyword virtual.. A non-virtual C++ member function is resolved during compile time or static binding. After the virtual function is declared.... When the class FourWheeler is derived or inherited from Vehicle and defined by the virtual function in the class FourWheeler....  Virtual function takes a different functionality in the derived class.... .. it is written as: .. 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.. Referring back to the Vehicle example. The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved. 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 { .. In this derived class..... detailed in an example below..... } }. } }. the new definition of the virtual function takes place. Virtual Functions are resolved during run-time or dynamic binding   Virtual functions are member functions of a class. Virtual functions are also simple member functions. For example.

the member function is declared virtual and the address is bounded only during run time. In this derived class. } }. b = new FourWheeler(). b->Make(). This v-table contains classes and pointers to the functions from each of the objects of the derived class. the compiler creates a v-table each time a virtual function is declared. making it dynamic binding and thus the derived class member function is called. the new implementation for virtual function Make() is placed. } In the above example. the base class member function is always called because linking takes place during compile time and is therefore static. The programmer might be surprised to see the function call differs and the output is then printed as above. } }. In this example.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 is derived from the base class Vehicle. This is used by the compiler whenever a virtual function is neede . If the member function has not been declared as virtual. *b. a = new Vehicle(). a->Make(). it is evidenced that after declaring the member functions Make() as virtual inside the base class Vehicle. void main() { Vehicle *a. class FourWheeler : public Vehicle { public: void Make() { cout<<"Virtual Member function of Derived class FourWheeler Accessed"<<endl. To achieve the concept of dynamic binding in C++.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->