BCS306B - Module 1
BCS306B - Module 1
Module - 1
An Overview of C++
Overview of C++:
C++ is an extension of C programming language.
C++ was first invented by ‘Bjarne Stroustrup’ in 1979 at Bell Laboratories, USA.
Initial name of C++ was “C with Classes”, renamed as C++ in 1983 by ‘Rick
Mascitti’
The invention of C++was necessitated by major programming factor: increasing
complexity.
C program is so complex that is difficult to grasp as a totality if the program exceeds
from 25000 10 100000 lines of code. C++ overcomes this problem.
C++ allows us to comprehend and manage larger, more complex programs.
Most additions made to C support Object-Oriented Programming (OOP).
Some features of OOP were inspired by another programming language Simula67. So
C++ is blending of two powerful languages C and Simula67.
First revision of C++ was made in the year 1985.
Second revision of C++ was made in the year 1990.
The first draft of the proposed standard C++ was jointly created by ANSI and ISO on
January 25th 1994.
The second draft of the proposed standard C++ was on November 11th 1997.
Final standard C++ became reality in 1998
C++ contains many advanced many new features along with the C features.
What is Object Oriented Programming (OOP)?
OOP is a powerful way to approach the job of programming. OOP was created to
help programmers break through the several C barriers.
To support the principles of OOP, all OOP languages have three traits in common:
Encapsulation, Polymorphism, and Inheritance. (These will explain in basic concepts of
OOPs in the next section).
Basic Concepts of OOPs:
It is necessary to understand some of the concepts used extensively in object-oriented
programming. These include:
• Objects
• Polymorphism
• Classes
• Data abstraction and encapsulation • Dynamic binding
• Inheritance • Message passing
Objects:
Objects are the basic run time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program has
to handle. Program objects should be chosen such that they match closely with the real-
world objects.
Classes:
A class is a specification describing a new data form and an object in a particular data
structure constructed according to the requirement. The entire set of data and a code of an
object can be made a user defined data type with the help of a class. In fact, objects are
variables of the type class. Once a class has been defined, we can create any number of
objects belonging to that class. Each object is associated with the data of type class with
which they are created. A class is thus a collection of objects of similar type.
Data Abstraction and Encapsulation:
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class can
access it. These functions provide the interface between the object’s data and the program.
This insulation of the data from direct access by the program is called data hiding or
information hiding.
Abstraction refers to the act of representing essential features without including the
background details of explanations. Classes use the concept of abstraction and are defined as
a list of abstract attributes like size, weight, cost, and functions to operate on these attributes.
They encapsulate all the essential properties of the objects that are to be created. The
attributes are sometimes called data members because they hold information. The functions
that operate on these data are sometimes called methods or member functions. Since the
classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification.
In OOP, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. The new class is
called child class (derived class). The old class is called parent class (base class). The child
class defines only the additional features and will have all the features of parent class. (Will
discuss this topic in Unit 5 and 6)
Polymorphism:
Polymorphism means the ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behaviors depend upon the types of
data used in operation. For example, consider the operation of addition. For two numbers,
the operation will generate a sum. If the operands are strings, then the operation would
produce a third string by concatenation.
The process of making a function to exhibit different behaviours in different
instances is known as function overloading. The process of making an operator to exhibit
different behaviors in different instances is known as operator overloading.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in
response to the call.
Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run-time. It is associated with polymorphism and
inheritance..
Message Passing:
An object-oriented program consists of a set of objects that communicate with each
other. The process of programming in an object-oriented language, therefore, involves the
following basic steps:
a) Creating classes that define objects and their behaviour.
b) Creating objects from class definitions, and
c) Establishing communication among objects.
A message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the function (message) and the information
to be sent.
Characteristics of OOP
i) Emphasis is on data rather than procedure
ii) Programs are divided into objects
iii) Data can be hidden and cannot be accessed by external functions.
iv) Objects may communicate with each other through functions.
v) New data and functions can be easily added whenever necessary.
vi) Follows bottom-up programming approach.
Benefits of OOPs:
• Through inheritance, we can increase reusability of code.
• We can build programs from the standard working modules that communicate with one
another, rather than having to start writing he code from scratch. This leads to saving of
development time and higher productivity.
• The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code in other parts of the program.
• It is possible to have multiple instances of an object to co-exist without any interference.
• It is possible to map objects in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects
• The data-centered design approach enables us to capture more details of a model in
implementable form.
• Message passing techniques for communication between objects makes the interface
descriptions with external systems much simpler.
• Software complexity can be easily managed.
• Object-oriented system can be easily upgraded from small to large systems.
Limitations of OOPs:
• Data is not freely available for all functions
• Data cannot move around the program or system to satisfy the requirement of individual
function.
Dr.Shivashankar.S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 3
BCS306B An Overview of C++ Module 1
bool (Boolean Type): Objects of type bool can store only the values true or false, which are
the keywords of C++. These true and false values are automatic conversions takes place to
integers (1 and 0 respectively) and vice versa. Specifically any non-zero value is converted
to true and zero is converted to false.
C89 doesnot define a Boolean type. C99 adds to C languages a type called bool with
the header file <stdbool.h>.
wchar_t (wide charater): wchar_t is an another built-in data type added to C++ in 1995. It
is an advance of data type char i.e., char supports 8 bit qualities where as in wchar_t
supports 16 bit qualities.
The wchar_t is used to hold a long character set associated with human languages.
The wchar_t type creates a wide character object.
Operators in C++:
C++ supports all the operators (Such as arithmatic, logical, relational, conditional,
assignment, increment/decrement, bitwise operators, and special operators like comma
operator, dot operator, arrow operator, * operator, & operator, and sizeof( ) operator)
available in C Programming. Along with these operators C++ provides following operator.
cascading an output operator, we should ensure necessary blank space between different
items.
The above cout statement can be written as two cout statements to give same output
effect i.e.,
cout << “SUM=”;
cout << sum;
Using the cascading technique, the last two statements can be combined as follows:
cout << “SUM = ” << sum << “\n” << “AVERAGE = ” << average << “\n” ;
Memory Management Operator:
The two operators new and delete are the C++ mechanism that perform dynamic
memory allocation and deallocation respectively. An advantage of using these operators
involve the existence of a data object or value created by new, until it is explicitly destroyed
by delete operator. Thus user has an explicit control over the allocation and deallocation of
memory for variables of fundamental types, arrays, structures etc., Since these operators
manipulate memory on the free store, they are also known as free store operators.
The new operator with the pointer to an object allocates memory for that object and
assigns the address of that memory to the pointer. But the delete operator does the reverse.
i.e., it returns the memory occupied by the object back to the heap.
The new operator can be used to create objects of any type. Syntax:
pointer-variable = new data-type;
Here, pointer-variable is a pointer of type data-type..
The new operator allocates sufficient memory to hold a data object of type data-type
and return the address of the object. The data-type may be any valid data type. The pointer-
variable holds the address of the memory space allocated. For example:
int *p = new int;
float *q = new float;
When a data object is no longer needed, it is destroyed to release the memory space
for reuse. The general form of its use is:
delete pointer-variable;
Since heap is finite, it can become exhausted. If there is insufficient memory to fill
an allocation request, then new will fail and a bad_alloc exception (generated by the header
new) will be generated.
Example: delete p;
Finally it frees the dynamically allocated memory by the delete operator only with
the valid pointer previously allocated by using the new.
If sufficient memory is not available for allocation the new returns a null pointer.
The new operator offers the following advantages over the function malloc( ).
1. It automatically computes the size of the data object. We need not use the operator
sizeof.
2. It automatically returns the correct pointer type, so that there is no need to use a type
cast.
3. It is possible to initialise the object while creating the memory space.
4. Like any other operator, new and delete can be overloaded.
Program to illustrate memory management operators (//new_del.cpp)
#include<iostream.h>
#include<new.h>
void main()
{ OUTPUT:
int *a = new int; Enter the values of a,b
int *b = new int; 4
int *sum = new int; 6
cout<<"Enter the values of a,b\n"; Sum = 10
cin>>*a>>*b;
*sum = *a + *b;
cout<<"Sum = "<<*sum<<endl;
delete a;
delete b;
getch();
}
For array Allocation:
ptr_var = new array_type[size];
delete [] ptr_var;
Example:
Ptr = new int[5];
delete [] ptr;
For object Allocation, will refer programs in later units.
cast operator (Type Casting):
Converting one type of data item to another type using an operator named cast is
called casting or type casting. Type casting in C++ is same as the type casting in C
Programming. (Refer C programming for more about type casting.
Syntax of type casting:
(type) expression; Or type (expression);
Example 1:
(float) x/2; // Here x/2 evaluates to type float
Example 2:
float ( x/2 ); // Here also x/2 evaluates to type float
Putting bracket either to datatype or to expression is called casting.
In C++, type cast is classified as 3 types.
1. const_cast 2. static_const 3. reinterpret_cast
Note: In this program when the change( ) is called, the value of x and y are passed
to a and b respectively. In such cases, the changes made inside the function affect the main
program. This is called as the function call by reference.
(Note: For more information, refer pointers in C Programming)
C++ Comments:
Comments are for programmers. It is a text or character string that can be placed
anywhere in the C++ program. It has no effect on program execution. C++ defines a new
symbol // (double slash) for introducing comments in a C++ program. The comment
statement can be continued to the end of line and there is no need for closing // symbol at
the end of the comment line.
The C++ comments can be written either at the beginning of a new line (i.e., starting
from first column) or on the same line following a program statement. For example,
// This program is to find the area of a circle
int a, b, c; //variables declared to be of integer type
C++ compiler also recognizes the C language comments which being with the
symbol /* and end with */
int sum=a+b+c; /*assignment statement to find sum*/
The C-style comments can spread on more than one line with single set of /* and */
symbols leading to multi-line comments.
Writing good comments, which are precise and concise, leads to a good
programming practice. This will help to understand the program easily and quickly.
The Class:
A class is a user defined data type consisting of private and public data members and
member functions in a single unit. It is the fundamental building block of object oriented
program.
A class definition contains two parts:
i) class head ii) class body
The class head is made up of the keyword class followed by the name of the class.
The class body is the portion of the class definition enclosed within a pair of curly braces.
The class body consists of both data and functions.
The data items used in a class are called data members and the functions defined
are called as member functions. The class definition is terminated by a semicolon(;).
The general form of a class declaration is:
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
creates a variable s of type student. In C++, the class variables are known as
objects. Therefore, s is called an object of type student. We may also declare more than
one object in one statement. For example:
student s1, s2, s3;
The declaration of an object is similar to that of a variable of any basic type. The
necessary memory space is allocated to an object at this stage.
Objects can also be created when a class is defined by placing their names
immediately after the closing brace, as we do in the case of structures. That is to say, the
definition
class student
{
………
} s1, s2, s3;
would create the object s1, s2 and s3 of type student.
Accessing Members:
A member function of a class can be called in two ways. First by an object of that
class followed by a dot operator followed by member function name. For example,
s.getdata( ); // Here, s is an object
s.putdata( );
Second by a pointer variable followed by an arrow operator followed by member
function name. For example, the function call
Ptr -> getdata( ); // Here, Ptr is a pointer variable
Ptr -> putdata( );
Defining Member Functions:
Member functions can be defined in two places:
• Inside the class definition
• Outside the class definition
It is obvious that, irrespective of the place of definition, the function should perform
the same task. Therefore, the code for the function body would be identical in both the
cases. But there is a subtle difference in the way the function header is defined.
Inside the class definition:
In this method defining a member function is to replace the function declaration by
the actual function definition inside the class. For example we could define the student class
as follows:
class student
{
int regno;
float percentage;
public:
void getdata()
{
cout << "Enter the register no. and Percentage \n";
members to public. The attempt to change the access specifier of private members to public
violates the concept of data hiding and encapsulation. So, we can overcome this problem by
declaring the non-member functions as friend functions to the class.
To make an outside function “friendly” to a class, we have to simply declare
this function as a friend of the class as shown below:
class ABC
{
…..
public:
......
friend void xyz(void); // friend function declaration
};
Important points to be observed while using ‘friend functions’:
• The function declaration should be preceded by the keyword friend.
• A friend function is not in the scope of the class to which it has been declared as friend.
• A friend function is just like a normal C++ function.
• A friend function can be declared either in the private or the public section of a class.
• Usually, a friend function has the objects as its arguments.
• A friend function cannot access the class members directly. An object name followed by
dot operator, followed by the individual data member is specified for valid access.
Example, if we want to access the member x of an object obj, then it specified as obj.x.
• Member functions of one class can be friend functions of another class.
• A function can be declared as a friend in any number of classes. A friend function,
although not a member function, has full access right to private member of the class.
A Program to illustrate friend function
class sample
{
int a, b;
public:
void setvalue()
{
a=25;
b=40;
}
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a + s.b)/2.0;
}
void main()
OUTPUT:
{
sample x; //object X Mean value = 32.5
x.setvalue();
cout<<"Mean value = " << mean(x) << "\n";
getch();
}
The friend function accesses the class variables a and b by using the dot operator
and the object passed to it. The function call mean(x) passes the object x by value to the
friend function.
Member functions of one class can be friend functions of another class. In such
cases, they are defined using the scope resolution operator, which is shown as follows:
class x
{
…..
int fun1( ); //member function of x
…..
};
class y
{
…..
friend int x :: fun1( ); //fun1 of x is friend of y
…..
};
The function fun1( ) is a member of class x and a friend class y
We can also declare all the member functions of one class as the friend function of
another class. In such cases, the class is called a friend class. This can be specified as
follows:
class Z
{
…..
friend class X; // All member functions of X are friend to Z
};
Write a program to compare the marks obtained by two students using two different classes.
class student2;
class student1
{
char name[10];
int marks;
public:
void getdata()
{
cout<<"\nEnter the name and marks\n";
cin>>name>>marks;
}
void putdata()
{
cout<<"\nName = "<<name<<"\nMarks = "<<marks<<endl;
}
friend void compare(student1 s1,student2 s2);
};
class student2
{
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 15
BCS306B An Overview of C++ Module 1
char name[10];
int marks;
public:
void invalue()
{
cout<<"\nEnter the name and marks\n";
cin>>name>>marks;
}
void outvalue()
{
cout<<"\nName = "<<name<<"\nMarks = "<<marks;
}
friend void compare(student1 s1,student2 s2);
};
void compare(student1 s1,student2 s2)
{
if(s1.marks > s2.marks)
cout<<"\nThe "<<s1.name<<" has scored more than " <<s2.name<<endl;
else
if(s1.marks < s2.marks)
cout<<"\nThe "<<s2.name<<" has scored more than " <<s1.name<<endl;
else
cout<<"\n"<<s1.name<<" and "<<s2.name<<" are scored equal marks\n";
} OUTPUT:
void main()
Enter data of student1
{
student1 std1; Enter the name and marks
Rama
student2 std2;
89
cout<<"Enter data of student1"; Enter data of student2
std1.getdata(); Enter the name and marks
cout<<"Enter data of student2"; Bheema
std2.invalue(); 87
cout<<"\nThe data of student1"; The data of student1
Name = Rama
std1.putdata();
Marks = 89
cout<<"\nThe data of student2";
The data of student2
std2.outvalue(); Name = Bheema
compare(std1,std2); Marks = 87
getch(); } The Rama has scored more than Bheema
The function compare( ) has arguments from both student1 and student2. When
the function compare( ) is declared as a friend in student1 for the first time, the compiler
will not acknowledge the presence of student1 unless its name is declared in the beginning
as
class student1; // This is known as ‘forward’ declaration.
As pointed out earlier, a friend function can be called by reference. In this case,
local copies of the objects are not made. Instead, a pointer to the address of the object is
passed and the called function directly worked on the actual object used in the call.
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 16
BCS306B An Overview of C++ Module 1
This method can be used to alter the values of the private members of a class.
Remember altering the values of private members is against the basic principles of data
hiding. It should be used only when absolutely necessary.
Inline functions:
One of the objectives of using functions in a program is to save memory space, when
a function is likely to be called many times. However, every time a function is called, it
takes a lot of extra time in executing a series of instructions for tasks such as jumping to the
function, saving registers, pushing arguments into the stack, and returning to the calling
function. When a function is small, a substantial percentage of execution time may be spent
in such overheads.
An inline function is a function that is expanded in line when it is invoked. That is,
the compiler replaces the function call with the corresponding function code i.e., each time
the actual code from the function is inserted into the program in place of function call
instead of taking jump into the function. The inline functions are defined as follows:
inline function-header
{
function body
}
Example:
inline double cube(double a)
{
return(a*a*a);
}
It is easy to make a function inline. All we need to do is to prefix the keyword inline
to the function definition. All inline functions must be defined before they are called.
Some of the situations where inline expansion may not work are:
1. For functions returning values, if a loop, a switch, or a goto exists.
2. For functions not returning values, if a return statement exists.
3. If functions contain static variables.
4. If inline functions are recursive.
Inline expansion makes a program run faster because the overhead of a function call
and return is eliminated. However, it makes the program to take up more memory because
the statements that define the inline function are reproduced at each point where the function
is called. So, a trade-off becomes necessary.
//Write a program to find the largest of three numbers using inline function
void main()
{
int a, b, c;
cout<<"Enter 3 numbers \n" ;
cin>> a >> b >> c;
large(a,b,c);
getch();
}
• A constructor does not return any value, so return type is not associated with its
definition (even void is not used).
• The programmer has no direct control over constructor functions.
• A constructor are not inherited
• The const or volatile class objects cannot be initialized with a constructor
• A constructor cannot be declared as virtual (Virtual functions).
• A constructor can be overloaded.
• Like other C++ functions, they can have default arguments.
• An object with a constructor (or destructor) cannot be used as a member of a union.
• They make ‘implicit calls’ to the operators new and delete when memory allocation is
required.
Types of Constructors:
✓ Default Constructor
✓ Parameterised Constructor
✓ Copy Constructor
✓ Dynamic Constructor
✓ Overloaded Constructor
Default constructors:
A constructor that accepts no parameters is called the default constructor. The
default constructor for class Sample is sample::sample( ). If no such constructor is
sample a; // Invokes the default constructor of the compiler to create the object a.
Program to illustrate default constructor
class box
{
int length, breadth, height;
public:
box(void)
{
length = breadth = height = 0;
}
void print(void)
{
cout << "length = " << length << endl;
cout << "breadth = " << breadth << endl;
cout << "height = " << height << endl;
}
};
void main()
{ OUTPUT:
box obj1; length = 0
obj1.print(); breadth = 0
getch(); height = 0
}
Parameterised constructors:
In practice it may be necessary to initialise the various data elements of different
objects with different values when they are created. C++ permits us to achieve this objective
by passing arguments to the constructor function when the objects are created. The
constructors that can take arguments are called parameterised constructors.
The constructor sample( ) may be modified to take arguments as shown
below:
class sample
{
int m, n;
public:
sample(int x, int y); // Parameterised Constructor
m = x;
n = y;
};
When a constructor has been parameterized, the object declaration statement such as
sample obj1;
may not work. We must pass the initial values as arguments to the constructor
function to which an object is declared. This can be done in two ways:
• By calling the constructor explicitly
• By calling the constructor implicitly
The following declaration illustrates the first method:
sample obj1 = sample(0, 100); //explicit call
This statement creates an sample object int1 and passes the values 0 and 100 to it.
The second is implemented as follows:
sample obj1(0, 100); //implicit call
This method, sometimes called the shorthand method, is used very often as it is
shorter, looks better and is easy to implement.
Remember, when the constructor is parameterised, we must provide
appropriate arguments for the constructor. The following program demonstrates the passing
of arguments to the constructor functions.
Program to illustrate parameterised constructor
class box
{
int length, breadth, height;
public:
box(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
}
void print(void)
{
cout << "length = " << length << endl;
cout << "breadth = " << breadth << endl;
cout << "height = " << height << endl;
}
};
void main() OUTPUT:
{ length = 2
box obj1(2,4,3);
breadth = 4
obj1.print();
height = 3
getch();
}
Copy Constructor:
A constructor can accept a reference to its own class as a parameter. For example,
sample(sample &i);
is valid. In such cases, the constructor is called the copy constructor.
A copy constructor is one which constructs another object by copying the
member of a given object. It is used to declare and initialise an object from another object.
For example, the statement
sample X2(X1);
would define the object X2 and at the same time initialise it to the values of X1.
Another form of this statement is
sample X2 = X1;
The process of initializing through a copy constructor is known as copy
initialization.
Program to illustrate copy constructor
class point
{
int x,y;
public:
point() //default constructor
{
x = y = 0;
}
point(int xp,int yp) //parameterized constructor
{
x = xp;
y = yp;
}
point(point &p) //copy constructor
{
x = p.x;
y = p.y;
}
void display()
{
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 21
BCS306B An Overview of C++ Module 1
cout << "x = " << x << "\t" << "y = " << y << endl;
}
};
void main()
{
point p1(20,30); //object p1 is created and initialised
point p2(p1); //copy constructor is called
point p3;
OUTPUT:
p1.display();
x = 20 y = 30
p2.display();
x = 20 y = 30
p3.display();
getch(); x = 0 y = 0
}
Destructor:
A destructor is a special member function which is also having the same name as
that of its class but prefixed with tilde(~) symbol. For example, if sample is the name of the
class then
~sample ( ); // is the destructor.
Characteristics of a Destructor:
• A destructor is invoked automatically by the compiler upon exit from the program
• A destructor does not return any value
• A destructor cannot be declared as static, const or volatile.
• A destructor does not accept any arguments and therefore cannot be overloaded.
• A destructor is declared in the public section of a class.
• If the constructor uses the new expression to allocate memory, then the destructor
should use the delete expression to free that memory.
Program to illustrate the destructors
class sample
{
int x;
public:
sample(void)
{
x = 0;
cout<< "In constructor, x = "<<x<<endl;
}
void printx(void)
{
x = 25;
cout<< "In printx, x = "<<x<<endl;
}
~sample()
{
cout<< "In destructor, object destroyed"<<endl;
}
};
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 22
BCS306B An Overview of C++ Module 1
void main()
{ OUTPUT:
sample s1; In constructor, x = 0
s1.printx( ); In printx, x = 25
getch(); In destructor, object destroyed
}
Static class members:
The main characteristic of the static variables is that it automatically
initialized to zero unless it has been initialized by some other value explicitly. In C++, static
member of a class can be classified into two types,
1. static data members
2. static member functions
Suppose, we want to maintain a single data item for a specific purpose for all objects
created for the class. If there is common item of information to be shared by all objects of
the same class then we can declare that item as static.
Static data members:
A data member of a class can be declared with the keyword static. A static
member variable has certain special characteristics. These are:
data1
data2
• A static data member is initialized to zero when the first object of its class is created.
No other initialisation is permitted.
• Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
• It is available only within the class, but its lifetime is the entire program.
Static variables are normally used to maintain values common to the entire class. For
example, a static data member can be used as a counter that records the occurrence of all the
objects.
Program to implement static class member.
class item
{
static int count;
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 23
BCS306B An Overview of C++ Module 1
int number;
OUTPUT:
public:
count:0
void getdata(int a)
{ count:0
number = a; count:0
count++; After reading data
} count:3
void getcount(void) count:3
{
cout << "count:" << count << "\n"; count:3
}
};
int item :: count;
void main( )
{
item a, b, c; //count is initialised to zero
a.getcount(); //display count
b.getcount();
c.getcount();
a.getdata(100); //getting data into object a
b.getdata(200); //getting data into object b
c.getdata(300); //getting data into object c
cout << "\n After reading data" << "\n";
a.getcount(); //display count
b.getcount();
c.getcount();
getch();
}
Notice the following statement in the program
int item :: count; //definition of static data member
Note that the type and scope of each static member variable must be defined
outside the class definition. This is necessary because the static data members are stored
separately rather than as a part of an object. Since they are associated with the class itself
rather than with any class object, they are also known as class variables.
Object 1 Object 2 Object 3
number number number
Sharing of a static data member
100 100 100
3
The static variable count is initialized to zero when the objects are created. The
count is incremented whenever the data is read into an object.
Since the data is read into objects three times, the variable count is incremented three
times. Because there is only one copy of count shared by all the three objects, all the three
output statements cause the value 3 to be displayed. The following figure shows how a static
variable is used by the objects.
Static variables are like non-inline member functions as they are declared in a
class declaration and defined in the source file. While defining a static variable, some initial
value can also be assigned to the variable. For instance, the following definition gives count
the initial value 10.
int item :: count =10;
Static Member Functions:
The keyword static is used to precede the member function to make a
member function static. A member function that is declared static has the following
properties:
• A static function can have access to only other static members (functions or
variables) declared in the same class.
• A static member function can be called using the class name (instead of its objects)
as follows:
class name :: function-name;
• The static member functions acts as global for members of its class with affecting
the rest of the program. The purpose of static member is to reduce the need for
global variables by providing alternatives that are local to a class. A static member
function is not part of objects of a class. Static members of a global have external
linkage.
A program to check how many instances of the class objects are created using the
static member function.
class sample
{
static int count; //static data member declaration
public:
sample();
static void display(); //static member function
};
//static data definition
int sample :: count;
inline sample :: sample()
{
count++;
}
inline void sample :: display( )
{
cout << "counter value = " << count << “\n”;
}
void main()
{
cout << "Before initialisation of the object \n ";
sample :: display();
sample obj1, obj2, obj3;
cout << "After initialisation of the object \n";
sample::display();
getch();
}
OUTPUT:
Before initialisation of the object
counter value = 0
After initialisation of the object
counter value = 3
When Constructors and Destructors are executed:
In C++, it is possible for a base class and derived class or both can contain
constructors and / or destructors. But it is very important to understand (know) the order of
invocation (calling) of these constructors and destructors when an object of derived class is
created and object of derived class is destroyed (deleted). This is also called as ‘Order of
invocation of Constructors and Destructors’.
Constructors are invoked in the order they have created and destructors are invoked
in the reverse order of they have created.
class box
{
int length, breadth, height;
public:
box()
{
cout<< “First Constructor Called”<<endl;
}
~box()
{
cout<< “First Destructor Called”<<endl;
}
box(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
cout<< “Second Constructor Called”<<endl;
}
~box()
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 26
BCS306B An Overview of C++ Module 1
{ OUTPUT:
cout<< “First Destructor Called”<<endl; First Constructor Called
} Second Constructor Called
void print(void) Second Destructor Called
{ First Destructor Called
cout << "length = " << length << endl; length = 2
cout << "breadth = " << breadth << endl; breadth = 4
cout << "height = " << height << endl; height = 3
}
};
void main()
{
box obj1(2,4,3);
obj1.print();
getch();
}
Scope Resolution Operator:
Scope resolution operator is an operator used to define the member function outside
the class. Scope resolution operator is denoted by a pair of Colon (i.e., ::). For Example.
class sum
{
int x, y;
public:
void read(int, int);
void print( );
};
void sum::read(int x, int y)
{
cout << ”enter the value of x and y\n”;
cin >> x >> y;
}
void sum::print( )
{
cout << ”The values of and b are: ” << x << ”\t” << b;
}
void main( ) OUTPUT:
{
The value of x is (inside main( ) ) = 20
sum s;
s.read( ); The value of x is (inside main( )) = 10
s.print( );
getch( );
}
Like C, C++ is also a block structured language. Blocks and scopes can be used in
constructing programs. We know that the same variable name can be used to have different
meanings in different blocks. The scope of the variable extends from the point of its
declaration till the end of the block containing the declaration. A variable declared inside a
block is said to be local to that block. Consider the following segment of a program:
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 27
BCS306B An Overview of C++ Module 1
……..
{
int x = 10;
{
int x = 1;
…….. Block 2 Block1
}
……..
}
The two declarations of x refer to two different memory locations containing
different values. The declaration inside the main( ). Block2 is contained in block1. Note that
a declaration in an inner block hides a declaration of the same variable in an out block and
therefore, each declaration of x causes it to refer to a different data object.
In C, the global version of a variable cannot be accessed from within the inner block.
C++ resolves this problem by introducing a new operator :: called scope operator. This can
be used to uncover a hidden variable. It takes the following form:
::variable-name
This operator allows to access the global version of a variable. For example, the
following illustrates the Scope Resolution Operator.
//Program to illustrates the declaration of scope resolution operator.
int x = 10; //global variable
void main()
{
int x = 20; //local variable
cout << "The value of x is (inside main( )) = "<< x;
cout << "\n";
cout << "The value of x is (outside main( )) = "<< ::x;
getch( );
}
In the above program variable x is declared at two places, namely, outside the main(
) function, inside the main( ), and inside the inner block. It is to be noted ::x will always
refer to the global x.
Scope resolution operator is also used in resolving the ambiguity in Multiple
Inheritance (Will be discussed later modules).
Scope resolution operator is also used in granting access in Inheritance (Will be
discussed later modules).
Passing Objects as function Arguments:
Like any other data type, an object may be used as a function argument. This can be
done in two ways:
• A copy of the entire object is passed to the function.
• Only the address of the object is transferred to the functions.
The first method is called pass-by-value. Since a copy of the object is passed to the
function, any changes made to the object inside the function do not affect the object used to
call the function. The second method is called pass-by-reference. When an address of the
object is passed the called function works directly on the actual object used in the call. This
means that any changes made to the object inside the function will reflect in the actual
object. The pass-by-reference method is more efficient since it requires to pass only the
address of the object and not the entire object. The following program illustrates the use of
function arguments.
Program to illustrate the objects as function arguments
class time
{
int hrs, min, sec;
public:
time()
{
hrs=0, min=0, sec=0;
}
time(int a, int b, int c)
{
hrs = a;
min = b;
sec = c;
}
void display()
{
cout<<hrs<<":"<<min<<":"<<sec<<endl;
}
void sum(time, time); //declaration with objects as arguments
};
void time :: sum(time t1, time t2)
{
sec = t1.sec + t2.sec;
min = sec/60;
sec = sec%60;
min = min+t1.min + t2.min; OUTPUT:
hrs = min/60; T1 = 2:45:40
min = min%60; T2 = 3:30:50
hrs = hrs + t1.hrs + t2.hrs; T3 = 6:16:30
}
int main()
{
time T1(2, 45, 40), T2(3, 30, 50), T3;
T3.sum(T1, T2); //T3 = T1 + T2
cout << "T1 = "; //display T1
T1.display();
complex A, B, C;
A.input(3.1, 5.65);
B.input(2.75, 1.2);
C = sum(A, B); //C = A + B
cout << "A = ";
A.show(A);
cout << "B = ";
B.show(B); OUTPUT:
A = 3.1 + i5.65
cout << "C = ";
B = 2.75 + i1.2
C.show(C); C = 5.85 + i6.85
getch();
}
Object Assignment
Assigning the values of one object to another is called object assignment. To assign the
value, both the source and destination objects must be created befor assigning.
#include <iostream.h>
class MyClass
{
public: int value;
MyClass(int val) : value(val)
{}
};
int main()
{
MyClass obj1(42);
MyClass obj2(0);
// Assign obj1's value to obj2
obj2 = obj1;
std::cout << "obj2's value: " << obj2.value << std::endl;
return 0;
}
Differences between Procedure Oriented Programming and Object Oriented
Programming:
Procedure Oriented Programming Object Oriented Programming
1) The primary focus is on doing things 1) The primary focus is on representing
via algorithm to perform the required data objects
computations.
2) Large programs are divided into smaller 2) Programs are divided into objects. Data
10) It supports multi-line comment 10) It supports both single-line (//) and
statement (i.e.,/* */) multi-line comment statement.
11) Example: C, Fortran, Cobol, Pascal 11) Example: C++, Visual Basic, Java,
J2EE