Está en la página 1de 26

C++ Tutorial.

For Beginners
(Taken from http:// cpp-tutorial.cpp4u.com/index.html)
This usage-oriented online C++ tutorial is intended to help you get your C++ experience on
the right foot. Using some Macromedia Flash animations where needed, you will find here all
the required information to get efficiently started on your usage of C++ language, independently
of the platform you are planning to use it on. After a short introduction aimed at getting you
started with the required tools to write and build C++ code source into executable binaries, you
will get thrown into the basics of C++ and its control structures, as an algorithmic starting point.
Still oriented on the usability, you will be pointed, along with detailed explanations, to the C-style
standard functions that can be used in your C++ source code to easien usual tasks. The tutorial
will then lead you into the Object Oriented paradigm on C++ language, which will be a must-
have in order to understand all the STL(Standard Template Library)-related info that you will find
in the last part of this tutorial.
// This is my first C++ program My first C++ program
//It prints a line of text
# include <iostream>
int main()
{
std::cout << “My first C++ program ” <<
std::endl;
return 0;
}

Structure of the C++ Program and C++ features


Above program demonstrates several important features of C++ language. The structure of the
program above is as follows:-

// This is my first C++ program


//It prints a line of text

are comments in C++ language.

# include <iostream>

is a preprocessor directive. It tells the preprocessor to include the contents of iostream header
file in the program before compilation. This file is required for input output statements.

main Function
int main() is a function. C++ program is a collection of functions. Every program in C++
begins executing at the function main(). Every C++ program has exactly one main function
and a collection of other functions.

A function is the main entity where all of the functionality of a program is defined. A function
takes some input, processes it according to the some code written in the function body and
produces an output which can be either sent to the user or can be used by other functions.
Keyword int in int main() specifies the return type of a function. int specifies that the
function main returns an integer value.

Brackets () after main signify that main is a function. Every function should be followed by a pair
of brackets. The purpose of brackets is to pass the parameters list to the functions. Parameters
are the number and type of arguments (inputs) which a function takes. Opening brace ( { ) and
closing brace ( } ) mark the beginning and end of a function. Anything which is inside the braces
is the body of that function.
In our example, the function body consists of only two statements,
{
std::cout << “My first C++ program. \n”;
return 0;
}

Statement
std::cout << “My first C++ program ” << std::endl;
The above line is a statement in C++. A statement must always terminate with a semicolon (;)
otherwise it causes a syntax error. This statement introduces two new features of C++
language, cout and << operator.

When this statement is executed, it sends the string between the quotation marks to the
standard output stream object – cout. cout is a predefined object in C++ and the standard
output stream is normally the screen.

The purpose of standard output stream object is to print the output on the device to which it is
connected. Normally, the output device is screen but it can be programmed to output to any
other device such as a printer. The following diagram illustrated the concept of cout.

User Screen
Monitor

Object Insertion Operator String variable

We used std:: before cout. This is required when we use # include <iostream> . It specifies
that we are using a name (cout) which belongs to namespace std. Namespace is a new
concept introduced by ANSI C++ which defines the scope of identifiers which are used in the
program. std is the namespace where C++ standard libraries are defined.

Operator << is the insertion stream operator. It sends contents of variable on its right to the
object on its left. In our case, right operand is the string “My first C++ program” and left operand
is cout object. So it sends the string to the cout object and cout object then displays it on the
output screen.

endl is the line feed operator in C++. It acts as a stream manipulator whose purpose is to feed
the whole line and then point the cursor to the beginning of the next line. We can use \n (\n is
an escape sequence) instead of endl for the same purpose. Then the code would be
std::cout << “My first C++ program \n”;
Return Statement
Last line in the body of our first program is
return 0;

The keyword return is a special statement which is used to exit a function and return a value.
This statement exits the function main indicating its completion and returns the value 0 to the
operating system indicating that the program successfully ran to completion. return statement is
included at the end of every main function.

Output
When this program is run, it prints the following output
My first C++ program

For programs to do exciting things, they should be written, compiled and then run on a computer
using a compile or IDE. Next tutorial, How to compile and run programs shows how to run
programs.

Congratulations!! You have just run your first C++ program and have understood many important
features of C++.

2.0 HOW TO WRITE AND COMPILE C++ PROGRAMS

In order to run a program and see it doing wonderful things, you should first write the program.
The program can be written in any text editor, such as vi and emacs in Unix environment and
using command prompt in DOS. There are also several Integrated Development Environment
(IDE) packages available which provide a complete programming environment for C++ in which
you can write, compile, run, and debug your program.

C++ programs are saved with extensions .C, .cc, .cpp, .cxx depending on the platform you are
working upon.

Once you have saved a program, next stage is compiling it using a compiler which converts
your C++ program into the object code which the computer can understand.

Compile using g++ compiler


If you are using UNIX environment and using g++ compiler, then compiling your C++ program is
simple. After you have saved the program file, simply type the command
g++ program.cc –o program

where program is the name of the program. For example the name of our first program is first,
then save it using extension “first.cc”. To compile, type
g++ first.cc –o first

To run the program, type first or ./first at the command prompt and your program will run.

Compile using DevC++ compiler


If you work on Windows and use DevC++, then editing and compiling is as easy as click of a
button. DevC++ is an IDE which allows you to edit, compile, run and debug your program in the
IDE itself. If you want to install DevC++ then install it from
http://prdownloads.sourceforge.net/dev-cpp/devcpp4980.exe.
1. Once you have installed and configured the software, Write and save your program
using DevC++ itself. Create a new program by clicking on New - Project.

2. Choose Empty Project from New Project dialog and choose a name for the program, in
our case first and click Ok.

3. Write the code of the program and save it.


4. Click on Compile button (third row, first button) to compile your source code. If there are
any errors in your program, then a window at the bottom will specify the warnings.
5. After program is compiled, click on Run button (next to compile).
6. However, DevC++ has a problem. As soon as you Run the program, output window
opens momentarily and then it closes. So to come around this solution, set a breakpoint
at the end of main function and then click on Debug instead of running it.

7. When you run the program, output window will show the string.
3.0 OOP FEATURES

Classes and objects and Methods and properties


A class is a user defined data type like a structure or a union. A class consists of data variables
and functions. These variables and functions are called members of the class. The variables
are called data members and functions are called member functions. The member functions are
also called methods. The data members are called properties of the class. An object is the
instance of the class. An object is like a compound variable of the user defined type. It links both
code and data. Within the object, members of the class can be public or private to the object.
The declaration of a class is syntactically same as structure. The class is declared using
keyword class.

The general form of the declaration of the class is:-

class class_name
{
access_specifier:
data functions
access_specifier:
data functions
} object_list;

The object_list is optional. The object_list is used to declare objects of the class. The
class_name is the name of the class. The access_specifier can either public, private or
protected. The members of the class by default are private to the class. If the
access_specifier is private then members of the class are not accessible outside the class.
If the access_specifier is public then members of the class can be accessed from outside
the class. The protected access_specifier is needed at the time of inheritance. The
members can be accessed using an object’s name, a dot operator and name of the member.
Here is a program which shows how classes and objects are created.

#include<iostream>
using namespace std;

class cube
{
public:
double side;
double volume()
{
return(side*side*side);
}
};
int main()
{
double volume1=0;
cube c1,c2;
cout << "Enter the lenght of the cube" << endl;
cin >> c1.side;
cout << "The volume of the cube is : " << c1.volume() << endl;
c2.side=c1.side +2;
cout << "The volume of the second cube is : " << c2.volume() <<
endl;
return(0);
}

The result of the program is:-

The program consists of a class cube which has data member side of type double and member
function which calculates the volume of the cube. The statement
class cube

declares a class cube. The statements

public:
double side;
double volume()
{
return(side*side*side);
}

declare that access_specifier is public for data member side and member function volume.
These members can be accessed from the other parts of the program. The statement
cube c1,c2;

declares two objects c1 and c2 of type cube. The statement

cin >> c1.side;

access the data member of the cube. The member is accessed by specifying the name of the
object as c1 then dot operator and then name of the variable side. The length entered by the
user is stored in c1.side. In the statement

cout << "The volume of the cube is : " << c1.volume() << endl;

c1.volume() calls the member function volume which returns the volume of the cube of side
whose length is entered by the user. The statement

c2.side=c1.side +2;
equates the side of object c2 to side of object c1 increased by 2. The objects c2 and c1 are
different. The statement

cout << "The volume of the second cube is : " << c2.volume() << endl;

displays the volume of second object c2.

Constructor and Destructor


Constructors are used in order to initialize the objects. A constructor is a special kind of a
function which is the member of the class. The name of the constructor is same as name of the
class. A constructor is automatically called when object is created. A constructor does not have
a return type.

A default constructor is a constructor with no parameters. If no constructor is defined by the user


then compiler supplies the default constructor. Once the constructor is defined by the user then
compiler does not supply default constructor and then user is responsible for defining default
constructor.

A destructor is the complement of the constructor. It is used to destroy the objects. The objects
are destroyed in order to deallocate the memory occupied by them. The name of the destructor
is same as the name of the constructor as is preceded by a tilt operator ‘~’. A destructor for
objects is executed in the reverse order of the constructor functions.

Here is a program which shows how constructors and destructors are used.

#include<iostream>
using namespace std;

class cube
{
public:
double side;
double volume()
{
return(side*side*side);
}
cube(double side1)
{
cout << "A constructor is called" << endl;
side=side1;
}
cube()
{
cout << "A default constructor is called " << endl;
}
~cube()
{
cout << "Destructing " << side << endl;
}
};
int main()
{
cube c1(2.34);
cube c2;
cout << "The side of the cube is: " << c1.side << endl;
cout << "The volume of the first cube is : " << c1.volume() << endl;
cout << "Enter the length of the second cube : " ;
cin >> c2.side;
cout << "The volume of second cube is : " << c2.volume() << endl;
return(0);
}

The result of the program is:-

The statement
cube(double side1)
{
cout << "A constructor is called" << endl;
side=side1;
}

declares the constructor of the class cube. The name of the constructor is same as the name of
the class. There is no return type in the constructor. It will initialize the value of data member
side. The statement
cube()
{
cout << "A default constructor is called " << endl;
}

declares a default constructor. The statement


~cube()
{
cout << "Destructing " << side << endl;
}

declares a destructor to deallocate the objects. The statement


cube c1(2.34);

creates an object c1 of type cube. A constructor is automatically called and initializes the data
member side with value 2.34. The statement
cube c2;

creates an object of type c2. When object c2 is created a default constructor is called and the
message will be printed.
The statements
cout << "The side of the cube is: " << c1.side << endl;
cout << "The volume of the first cube is : " << c1.volume() << endl;

displays the side and volume of the cube where side has value 2.34. The statement
cin >> c2.side;

will set the value of the side of the object c2 as entered by the user. At the end of the program
objects are deallocated in the reverse order in which constructors are called. First object c2 is
deallocated whose side is 2.5 and then object c1 is deallocated whose side is 2.34.

Advantage of the classes


It provides protection to the data. The members of the class are by default private to the class
while the members of the structure are public. OOP features allow programmer to easily handle
complex problems and multi file projects. They help in modeling real world objects such as bank
accounts and their related transactions.

4.0 ENCAPSULATION, PRIVATE PUBLIC. SECTIONS

The packaging of data values and member functions within one object is called an
encapsulation. For example an object of class cube contains data member as side of the cube
and member function volume of the cube. It is also called data hiding which helps to maintain
the integrity of the object. It saves the data from misuse and outside interference. The data
cannot be accessed directly but access controls can be specified in order to obtain the
information. The data or object can be made public or private depending on the needs. The data
which is private is not accessible outside the scope of the object. When the data is public it can
be accessed by the other parts of the program.

Here is a program which shows how private and public members are accessed. The program
consists of a class rectangle which has two data members such as length and breadth and the
member functions area() and len(). The private data member length cannot be accessed
directly. It is accessed using a function len() which is public and which returns the private data
member length.

#include<iostream>
using namespace std;

class rectangle
{
private:
double length;

public:
double breadth;
double area()
{
return(length*breadth);
}
double len()
{
return(length);
}
rectangle(double lenght1,double breadth1)
{
length=lenght1;
breadth=breadth1;
}
};

int main()
{
rectangle r1(3.5,4.6);
double a=r1.len();
double b=r1.breadth;
cout << "The lenght is : " << a << endl;
cout << "The breadth is : " << b << endl;
cout << "The area is : " << r1.area() << endl;
return(0);
}

The result of the program is:-

The statement
private:
double length;

declares that data member length of type double which has access specifier as private. It
cannot be accessed directly. The statements

public:
double breadth;
double area()
{
return(length*breadth);
}
double len()
{
return(length);
}

declares that data member breadth and member functions len() and area() are public. The
member function len() is used to return the data member length which cannot be accessed
directly. The statement
rectangle r1(3.5,4.6);
declares an object r1 of rectangle. The constructor initializes the length and breadth of the
object as soon as it is created. The statement
double a=r1.len();

returns the length of the object. The data member length cannot be accessed directly as it is
declared private therefore member function len() is used to return the value of length. The
statement double a=r1.length in main() function is invalid as data member length is
inaccessible. The statement
double b=r1.breadth;

equates the value of b to the value of breadth of object r1. The statement
cout << "The area is : " << r1.area() << endl;

displays the area of the rectangle.

5.0 INHERITANCE: SAMPLES OF USING INHERITANCE

Inheritance is the property by which one object can inherit the properties of the other object. A
general class can be inherited by the other classes. A class that is inherited is called a base
class. A class which is inheriting another class is called a derived class. When a class inherits
another class, members of the base class become the members of the derived class. The
general form of inheritance is:-

class derived_name : access_specifier base_name


{
};

The derived_name is the name of the derived class. The base_name is the name of the base
class. The access_specifier can be private, public or protected. If the access_specifier is
public then all public members of the base class become public members of the derived class
and protected members of the base class become the protected members of the derived class.
If the access_specifier is private then all public and protected members of the base class will
become private members of the derived class. If the access_specifier is protected then the
public and protected members of the base class become the protected members of the derived
class. Whether access_specifier is public, private or protected, private members of the base
class will not be accessed by the members of the derived class.

The access_specifier protected provides more flexibility in terms of inheritance. The private
members of the base class cannot be accessed by the members of the derived class. The
protected members of the base class remain private to their class but can be accessed and
inherited by the derived class. The protected members of the base class will remain private to
the other elements of the program.

A derived class can inherit one or more base classes. A constructor of the base is executed first
and then the constructor of derived class is executed. A destructor of derived class is called
before the destructor of base class. The arguments to the base class constructor can be passed
as follows:-
derived_constructor (argument list): base1 (arg_list)
base2(arg_list1)
baseN(arg_list)

The derived_constructor is the name of the derived class. The argument list is list of the data
members of the derived class. The base1 is name of the base class. The arg_list is the list of
the members of the base class. Here is a program which illustrates the features of inheritance.

#include<iostream>
using namespace std;

class shape
{
private :
double length;
protected:
double breadth;
public :
double len()
{
return(length);
}
shape(double length1,double breadth1)
{
length=length1;
breadth=breadth1;
}
//shape() { }
};

class shape1
{
public:
double height;
shape1(double height1)
{
height=height1;
}
//shape1() { }
};

class cuboid : public shape, private shape1


{
public:
cuboid(double length1,double breadth1,double height1):
shape(length1,breadth1),shape1(height1)
{
cout << " A constructor is called " << endl;
}

double volume()
{
return(height*breadth*len());
}
double bre()
{
return(breadth);
}
double ht()
{
return(height);
}
};

int main()
{
cuboid c1(2.4,3.5,6.7);
cout << "The length of the cuboid is : " << c1.len() << endl;
cout << "The breadth of the cuboid is : " << c1.bre() << endl;
cout << "The height of the cuboid is : " << c1.ht() << endl;
cout << "The volume of the cuboid is : " << c1.volume() << endl;
return(0);
}

The result of the program is:-

The program has two base classes shape and shape1 and one derived class called cuboid
which inherits shape as public and shape1 as private. The public and protected members of
shape become public and protected members of derived class cuboid. The private members of
shape remain private to the class shape. The members of shape1 class become the private
members of the derived class cuboid.

The statement

class cuboid : public shape, private shape1

states that class cuboid inherits class shape as public and class shape1 as private. The
statement

cuboid(double length1,double breadth1,double height1):


shape(length1,breadth1),shape1(height1)
{
cout << " A constructor is called " << endl;
}

declares the constructor of the class cuboid. When constructor of class cuboid is called first
constructor of shape is executed and then constructor of shape1 is executed and after that the
constructor of cuboid is executed.
The statements

double volume()
{
return(height*breadth*len());
}

calculate the volume of the cuboid. The class cuboid cannot access the private data member
length of the shape class. It access the length by calling the function len() which returns the
private data member length. The data member breadth becomes the protected member of
the class cuboid. The height which is public member of shape1 class becomes the private
member of the class cuboid as it inherits the shape1 class as private. The statements

double bre()
{
return(breadth);
}

returns the breadth of the cuboid as data member breadth cannot be accessed outside the
class as it is protected member of cuboid. The statement

double ht()
{
return(height);
}

returns the height of the cuboid as data member height cannot be accessed outside the
class as height is the private data member of the class cuboid. The statement

cuboid c1(2.4,3.5,6.7);

creates an object c1 of type cuboid. The constructor is called to initialize the values of the
cuboid. The constructor of shape is executed and then constructor of shape1 is executed and
then finally constructor of cuboid is executed. The statement

cout << "The length of the cuboid is : " << c1.len() << endl;

displays the length of the cuboid as c1.len() calls the len() function of class shape which
is also the public member function of cuboid. The statement

cout << "The breadth of the cuboid is : " << c1.bre() << endl;

displays the breadth of the cuboid. As the data member breadth cannot be accessed directly
as it is protected member of the class cuboid so the function bre() returns the breadth of the
cuboid. The statement

cout << "The height of the cuboid is : " << c1.ht() << endl;

displays the height of the cuboid. The data member height cannot be accessed directly as it is
private member of class cuboid so it is accessed through the function ht() which returns
height.
6.0 POLYMORPHISM AND VIRTUAL FUNCTIONS

Polymorphism is defined as one interface to control access to a general class of actions. There
are two types of polymorphism one is compile time polymorphism and the other is run time
polymorphism. Compile time polymorphism is functions and operators overloading. Runtime
time polymorphism is done using inheritance and virtual functions.

Function Overloading
Polymorphism means that functions assume different forms at different times. In case of
compile time it is called function overloading. For example, a program can consist of two
functions where one can perform integer addition and other can perform addition of floating
point numbers but the name of the functions can be same such as add. The function add() is
said to be overloaded. Two or more functions can have same name but their parameter list
should be different either in terms of parameters or their data types. The functions which differ
only in their return types cannot be overloaded. The compiler will select the right function
depending on the type of parameters passed. In cases of classes constructors could be
overloaded as there can be both initialized and unintialized objects. Here is a program which
illustrates the working of compile time function overloading and constructor overloading.

#include<iostream>
using namespace std;

class employee
{
public:
int week;
int year;
double calculate(double salary)
{
return(salary*week);
}
int calculate(int salary)
{
return(salary*week*year);
}
employee(int week1)
{
week=week1;
}
employee(int week1,int year1)
{
week=week1;
year=year1;
}
};
int main()
{
int sal;
double sal2;
employee emp1(10);
employee emp2(10,3);
cout << "Enter the no years for first employee" << endl;
cin >> emp1.year;
cout << endl << "Enter the salary per week for first employee" << endl;
cin >> sal;
cout << "The total salary of first employee is : "
<< emp1.calculate(sal) << endl;
cout << endl << "Enter the salary per week for second employee is : "
<< endl;
cin >> sal2;
cout << "The total salary of second employee is for one year: "
<< emp2.calculate(sal2) << endl;
return(0);
}

The result of the program is:-

In the program function calculate() and constructor of class employee are overloaded. The
function calculate() is declared two times but with different parameter type and same with
constructor employee which is also declared two times but with different parameter types. The
following statements

double calculate(double salary)


{
return(salary*week);
}
int calculate(int salary)
{
return(salary*week*year);
}

declare functions with same name calculate but one has parameter type integer and other has
parameter type double. The function calculate() is overloaded. The statements

employee(int week1)
{
week=week1;
}
employee(int week1,int year1)
{
week=week1;
year=year1;
}

declare two constructors of class employee where one constructor’s parameter list is different
from other constructor’s parameter list. The constructor is overloaded. The statement

employee emp1(10);

declares an object emp1 of type employee. When object is created first constructor is called
since the argument list matches with parameter list of the constructor. The constructor initializes
the data member week of the object emp1. The statement

employee emp2(10,3);

declares an object emp2 of type employee. The second constructor is called since the argument
list matches with the parameter list of the constructor. The constructor initializes the data
members week and year of the object emp2. In the statement

cout << "The total salary of first employee is : "


<< emp1.calculate(sal) << endl;

emp1.calculate(sal) calls the first function calculate as the data type of sal matches with the
parameter of the function calculate. It displays the total salary which is salary*week*year. In
the following statement

cout << "The total salary of second employee is for one year: "
<< emp2.calculate(sal2) << endl;

emp2.calculate(sal2) calls the second function calculate as the data type of sal2 which is
double matches with the data type of parameter of function calculate and hence second
function is called. It displays the total salary which is salary*week.

Operator Overloading
In polymorphism operators can also be overloaded. Operators can be overloaded in order to
perform special functions with respect to the class. With the help of operator overloading
standard operations such as + , - , * , etc can be applied on the objects of the class.
Operators are overloaded by creating operator functions. The keyword operator is used to
define operator function. Operator overloading doesn’t allow creating new operators. The
general form of operator function is:-

return_type operator #(arg_list)


{
}

return_type is the data type of the value returned from the function. The arg_list is the list of
the arguments to the function. The operator comes after the keyword operator. Instead of #
there will be an operator. Here is a program to show operator overloading.
#include<iostream>
using namespace std;

class rectangle
{
public:
int length;
int breadth;

rectangle(int length1,int breadth1)


{
length=length1;
breadth=breadth1;
}

int operator+(rectangle r1)


{
return(r1.length+length);
}
};

int main ()
{
rectangle r1(10,20);
rectangle r2(40,60);
int len;
len=r1+r2;
cout << "The total length of the two rectangles is : " << len
<< endl;
return(0);
}

The result of the program is:-

The program consists of operator + function which is overloaded. The + operator is used to
perform addition of the length of the objects. The statements

int operator+(rectangle r1)


{
return(r1.length+length);
}

define the operator function whose return type is integer. The operator + is overloaded. The
function is used to add the lengths of the two objects. The parameter list consists of one object
of type rectangle. The operator()+ takes only one parameter as the operand on the left side
of the operator + is passed implicitly to the function through the this operator. The statement
len=r1+r2;

calls the operator()+ function to calculate the length of the two objects. The return type is of
integer. The variable len will contain the total of length of the objects.

Virtual Functions
A virtual function is a member function of the base class and which is redefined by the derived
class. When a derived class inherits the class containing the virtual function, it has ability to
redefine the virtual functions. A virtual function has a different functionality in the derived class.
The virtual function within the base class provides the form of the interface to the function.
Virtual function implements the philosophy of one interface and multiple methods. The virtual
functions are resolved at the run time. This is called dynamic binding. The functions which are
not virtual are resolved at compile time which is called static binding. A virtual function is created
using the keyword virtual which precedes the name of the function.

Virtual functions are accessed using a base class pointer. A pointer to the base class can be
created. A base class pointer can contain the address of the derived object as the derived
object contains the subset of base class object. Every derived class is also a base class. When
a base class pointer contains the address of the derived class object, at runtime it is decided
which version of virtual function is called depending on the type of object contained by the
pointer. Here is a program which illustrates the working of virtual functions.

include<iostream>
using namespace std;

class shape
{
public:
int side;

virtual int volume()


{
cout << endl <<"Virtual function of base class " << endl;
return(0);
}
};

class cube: public shape


{
public:
int volume()
{
cout << endl << "Volume function of cube " << endl;
return(side*side*side);
}
};
class cuboid:public shape
{
public:
int breadth;
int height;
int volume()
{
cout << endl << "Volume function of cuboid " << endl;
return(side*breadth*height);
}
};

int main()
{
shape *s,s1;
cube c1;
cuboid c2;
cout << "Enter the side of the cube" << endl;
cin >> c1.side;
cout << endl << "Enter the side of the cuboid " << endl;
cin >> c2.side;
cout << endl << "Enter the breadth of the cuboid" << endl;
cin >> c2.breadth;
cout << endl << "Enter the height of the cuboid" << endl;
cin >> c2.height;
s=&s1;
s->volume();
s=&c1;
cout << endl << "The volume of the cube " << s->volume() << endl;
s=&c2;
cout << endl << "The volume of the cuboid " << s->volume() << endl;
return(0);
}

The result of the program is:-


The program has base class shape and class cube and cuboid which inherits base class. The
base class has virtual function volume. The statements

virtual int volume()


{
cout << endl <<"Virtual function of base class " << endl;
return(0);
}

define the member function volume() of base class. The function is virtual. The keyword virtual
precedes the function return type. In the following statements

int volume()
{
cout << endl << "Volume function of cube " << endl;
return(side*side*side);
}

the derived class cube which inherits base class shape, redefines the function volume() which
is virtual. In the following statements

int volume()
{
cout << endl << "Volume function of cuboid " << endl;
return(side*breadth*height);
}

the derived class cuboid which inherits the base class shape, redefines the function volume().
The statement

shape *s,s1;

declares a pointer to the base class shape. The statement

s=&s1;

pointer s contains the address of the base class object s1. The statement

s->volume();

calls the function volume of the base class shape as the pointer contains the address of the
base class object. The statement

s=&c1;

pointer s now contains the address of the derived class object c1. The statement

cout << endl << "The volume of the cube " << s->volume() << endl;
displays the volume of the cube as s->volume() calls the function volume of the derived class
cube. The pointer s contains the address of the object of derived class cube. In the statement

s=&c2;

pointer s now contains the address of the derived class object c2. The statement

cout << endl << "The volume of the cuboid " << s->volume() << endl;

displays the volume of the cuboid as s->volume() calls the function volume of the derived
class cuboid. The pointer s now contains the address of the object of derived class cuboid.

When a virtual function is not defined by the derived class, the version of the virtual function
defined by the base class is called. When a derived class which contains the virtual function is
inherited by another class, virtual function can be overloaded for the new derived class. This
means that virtual function can be inherited.

A pure virtual function is a function which contains no definition in the base class. The general
form of virtual function is:-

virtual return_type function_name(para_list)=0;

The return_type is the type of the value returned. The function_name is the name of the
function and para_list is the parameter list.

Each derived class should contain the definition of virtual functions. If the derived class does not
define virtual function then compiler will generate an error. A class which contains one or more
pure virtual function is called abstract class. Objects of abstract class cannot be created as it
does not contain definition of one or more functions. The pointers of abstract class can be
created and the references to the abstract class can be made. Here is a same program which
shows how pure virtual function is defined.

#include<iostream>
using namespace std;

class shape
{
public:
int side;
virtual int volume()=0;

};

class cube: public shape


{
public:
int volume()
{
cout << endl << "Volume function of cube " << endl;
return(side*side*side);
}
};
class cuboid:public shape
{
public:
int breadth;
int height;
int volume()
{
cout << endl << "Volume function of cuboid " << endl;
return(side*breadth*height);
}
};

int main()
{
shape *s;
cube c1;
cuboid c2;
cout << "Enter the side of the cube" << endl;
cin >> c1.side;
cout << endl << "Enter the side of the cuboid " << endl;
cin >> c2.side;
cout << endl << "Enter the breadth of the cuboid" << endl;
cin >> c2.breadth;
cout << endl << "Enter the height of the cuboid" << endl;
cin >> c2.height;
s=&c1;
cout << endl << "The volume of the cube " << s->volume() << endl;
s=&c2;
cout << endl << "The volume of the cuboid " << s->volume() << endl;
return(0);
}

The result of the program is:-


The statement

virtual int volume()=0;

declares pure virtual function volume() which has no definition. The class shape is now
abstract class and objects of type shape cannot be created.

También podría gustarte