0% found this document useful (0 votes)
16 views33 pages

BCS306B - Module 1

This document provides an overview of C++, detailing its history, features, and principles of Object-Oriented Programming (OOP). It covers key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, along with their benefits and limitations. Additionally, it includes examples of C++ syntax, data types, operators, and memory management techniques.

Uploaded by

singhmahip688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views33 pages

BCS306B - Module 1

This document provides an overview of C++, detailing its history, features, and principles of Object-Oriented Programming (OOP). It covers key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, along with their benefits and limitations. Additionally, it includes examples of C++ syntax, data types, operators, and memory management techniques.

Uploaded by

singhmahip688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

BCS306B An Overview of C++ 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.

Dr.Shivashankar.S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 1


BCS306B An Overview of C++ Module 1

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.

Dr.Shivashankar.S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 2


BCS306B An Overview of C++ Module 1

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

• Defined action can only be implemented on associated data members. Instantaneously, it


is not possible to define random actions.
• Sometimes one may not feel it convenient to write programs if data members and
functions could not be separated out.
• For every new operation, user or programmer must define a member function and
appropriate changes must reflect in class definition.
• OOP is thus complex and tedious if one does not know the design features of his problem
to be solved interns of objects and its methods.
Application of OOPs:
• Real-time systems and online application systems such as Air traffic control, Airline seat
reservation, Railway ticket reservation, Bank transactions etc.,
• Simulation and modeling of vehicle design and performance in motor industry.
• Object-oriented database design and applications.
• Multimedia, Hypertext, hypermedia applications and other internet applications.
• Neural networks and parallel programming
• Office automation and data processing systems
• CIM / CAM / CAD systems.
Sample C++ Program:
#include<iostream.h>
class Sample
{
public:
void display( )
{
cout << “ This is my first program in C++ \n ”;
} };
void main( )
{
Sample s; OUTPUT:
This is my first program in C++
s.display( );
getch( );
}
Here, iostream.h - is an header file in C++ like stdio.h in C
class - is a keyword
Sample - is a class
public - is a keyword (which is a access specifier /visibility mode)
cout - is a keyword used for printing (Same as printf( ))
<< - is an insertion (output) operator. Can take any datatype like C.
}; - Indicates end of the class.
s - is an object of class Sample
s.display( ) - is the way of access the member function in C++.
Different Data types:
C++ supports all the basic datatypes (Such as int, float, char, double, and void)
available in C Programming. Along with these data types, C++ provides two buil-in data
types. Such as bool, and wchar_t.

Dr.Shivashankar.S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 4


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.

• << operator • cast operator


• >> operator • Memory Management operator
Input Operator (<<):
The symbol >> is called an extraction operator. The >> operator for accepting
standard data types viz., int, float, char, double, long etc., The input operator >> sends the
data on its right . For example,
cin >> radius;
which causes the program execution to wait for the user or programmer to type in a number
or numeric value as radius of a circle. Consider another example,
cin >> a>>b>>c;
The output statement cout prompts the user to type-in 3 integer numbers. If we enter
the numbers 3 2 4 the first operator >> takes value 3 from its stream object cin and places
it in the variable a that follows on its right. A second operator >> reads a value 2 and stores
it in the variable b. Similarly third operator >> extracts a value 4 from its input stream on its
left and copies it into third variable c.
The multiple use of >> in statement is known as cascading.
Output Operator (<<):
The output operator << is called the insertion or put to operator. It inserts the
contents of the variable on its right to the object on its left.
We can also include variables with single cout whose contents are displayed
simultaneously. For example,
cout << “SUM =”<<sum << “\n”;
first sends the string “SUM =” to cout and then sends the value of sum. Finally it sends the
new line character. The multiple use of << in one statement is called cascading. When
Dr.Shivashankar.S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 5
BCS306B An Overview of C++ Module 1

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.

Dr.Shivashankar.S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 6


BCS306B An Overview of C++ Module 1

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

Dr.Shivashankar.S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 7


BCS306B An Overview of C++ Module 1

Function and its Components:


A function is a self-contained block or a sub-program of one or more statements that
perform a special task when called.
User Defined Functions:
In addition to the standard library functions supplied by the C++ system, the user can
define a function according to his requirement are called as user-defined functions.
Programmer can write his own function to perform a specific sub-task. Just as you define a
main( ) function. Function definition begins with a name and a set of statements enclosed in
braces. The user can modify the function according to the requirement.
Actual arguments and Formal arguments:
These are used as a means for communication between user defined functions and
the main( ) function. The variables to be passed to the functions are called actual
arguments, they are enclosed in a parentheses following the functions name. They may
have to either convey input values necessary for computations within the user-defined
function or they may be used to return the computed results from user-defined functions to
main( ) function.
The formal arguments, which receives the value of the actual arguments or address
of the actual arguments from the main program and send to the body of the user defined
function for specified operation.
Return Statement:
A function can display the results after computation by including a cout statement
within it. Sometimes user may wish after that the results need no to be printed by the
function itself, instead let the function return the result to its main function (calling routine).
The general format of return statement is return (value);
The return statement when executed from within a user-defined function returns the
value. This value may be a constant, variable or expression that represents useful results of
computation. This statement specifies that the function has to return a value to its calling
function. Therefore if the function has to return a value to its calling routine, then the last
statement executed in the function definition must be a return statement.
Function Declaration:
Function declaration means specifying the function as a variable depending on the
return value. It is declared as the part of the main program. It helps the compiler to treat
functions differently from other program elements. A function declaration has two principal
components, one the name of the function and the pair of parenthesis with or without
arguments. The arguments are called formal arguments, because they represent the names
of the data items that are transferred into the function from the calling portion of the
program. The identifiers used as formal arguments are ‘local’ in the sense that they are not
recognized outside the function. Hence, the names of the arguments need not be the same as
the names of the actual arguments in the calling portion of the program, however it must be
the same data type.

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 7


BCS306B An Overview of C++ Module 1

write a program to add two numbers by user-defined function


int add(int x, int y); // Function Prototype
void main() OUTPUT:
{ Enter the values of a and b:
int a, b, sum; 6
4
cout << "Enter the values of a and b:\n";
The sum of a and b = 10
cin >> a >> b;
sum=add(a,b); // Function Declaration, a and b are actual arguments
cout << "The sum of a and b = " << sum;
getch();
}
int add(int x, int y) // Function Definition, x and y are Formal Arguments
{
return(x + y); //The return statement, returns sum of x+y to main function
}
Explanation of the above program:
a, b - Actual arguments or Arguments
x, y - Formal Arguments or Formal Parameters or Local Parameters
void main( ) - The calling function
int add( ) - The int is the return type of the return value
int add(int x,int y) - The called function.
return - It is a keyword to send the output of the function back to the
calling function.
{ - beginning of the main function or user defined function
} - end of the main function or user defined function
body of the function - all the statements placed between { and }
▪ The number of the actual arguments should be equal to number of formal arguments.
▪ There must be one-to-one mapping between arguments ie., they should be in the same
order and should be in same data type.
▪ In the above example program a, and b are arguments are copied to the corresponding
parameters x and y. They are all of the same data type int. here, a corresponds to x, and
b corresponds to y.
Argument Passing:
Like other parameters, pointers can be passed as arguments to functions. This is
carried out by the call by reference parameter passing method.
There are two ways in which we can pass arguments to the function.
i) Call by value ii) Call by reference
i) Call by Value:
In this type value of actual arguments are passed to the formal arguments and the
operation is done on the formal arguments. Any change made in the formal argument does
not affect the actual arguments because formal arguments are photocopy of actual
arguments. Changes made in the formal arguments are local to the block of the called
function. Once control returns back to the calling function the changes made vanish.

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 8


BCS306B An Overview of C++ Module 1

Write a program to send values using call by value procedure


void main( )
{
int x,y;
cout << "Enter the values of x and y:\n";
cin >> x >> y;
change(x,y);
cout << "In main() x = ” << x << “ y = ” << y;
return 0;
} OUTPUT:
void change(int a, int b) Enter the values of x and y:
{ 6
int temp; 9
temp = a; In change( ) x=9 y=6
a = b; In main( ) x=6 y=9
b= temp;
cout << "In change() x =” << a << “y = ”<< b;
}
Note: In this program when the swap( ) is called, the value of x and y are passed to a and b
respectively. In such cases, the changes made inside the function cannot affect the main
program. This is called as the functions call by value.
ii) Call by Reference:
The variables are stored somewhere in memory. Instead of passing the value of the
variables we can pass the address of the variable. Here, the formal arguments are pointers to
the actual arguments. In this type formal arguments point to the actual argument. Hence
changes made in the arguments are permanent.
Write a program to send values using call by reference procedure
void main()
{
int x,y;
OUTPUT:
cout << "Enter the values of x and y:\n";
Enter the values of x and y:
cin >> x >> y;
4
change(&x, &y);
8
cout << "In main( ) x = ” << “y = ” << y;
In change() x=8 y=4
getch();
In main() x=8 y=4
}
void change(int *a, int *b)
{
int *temp;
*temp = *a;
*a = *b;
*b= *temp;
cout << “In change() x = ” << *a << “ y = ” << *b;
}

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 9


BCS306B An Overview of C++ Module 1

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;
};

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 10


BCS306B An Overview of C++ Module 1

Private and Public: (Data Hiding)


A key feature of object-oriented programming is data hiding. This means, the data is
concealed within a class. The primary mechanism for hiding data is to put it in a class and
make it private. The private data and functions can only be accessed within the class.
Public data or functions on the other hand are accessible from outside the class. The
keyword private and public are known as visibility labels. These keywords are followed by
a colon.
The use of the keyword private is optional. By default, the members of a class are
private. If both the labels are missing, then, by default, all the members are private. Such a
class is completely hidden from the outside world and does not serve any purpose.
class student
{
int regno;
char name[10];
public: void getdata()
{
cout << "Enter the register no.\n";
cin >> regno;
cout << "Enter the name\n";
cin >> name;
}
void putdata()
{
cout << "Register No.: " << regno << “\n”;
cout << "Name : " << name << “\n”;
}
OUTPUT:
};
void main() Enter the register no.
{ 3456
student s; Enter the name
Shivashankar
s.getdata(); Register No.: 3456
s.putdata(); Name : Shivashankar
getch(); }
We usually give a class some meaningful name, such as student. This name now
becomes a new type identifier that can be used to declare instances of that class type. The
class item contains two data members and two function members. The function getdata( )
can be used to assign values to the member variables number and cost, and putdata( ) for
displaying their values. The data members are usually declared as private and the member
functions as public.
Creating Objects:
Once a class has been declared, we can create variables of that type by using the
class name (like any other built-in type variable). For example,
student s; //memory for s is created

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 11


BCS306B An Overview of C++ Module 1

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";

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 12


BCS306B An Overview of C++ Module 1

cin >> regno >> percentage;


}
void putdata()
{
cout << "Reg No.: "<< regno << " \nPercetage : " << percentage;
}
};
When a function is defined inside a class, it is treated as an inline function.
Therefore, all the restrictions and limitations that apply to an inline function are also
applicable here.
Outside the class definition:
Member functions that are declared inside a class have to be defined separately
outside the class. Their definitions are very much like the normal functions. They should
have a function header and a function body.
An important difference between a member function and a normal function is that a
member function incorporates a membership ‘identity label’ in the header. This ‘label’ tells
the compiler which class the function belongs to. The general form of a member function
definition is:
return-type class name :: function-name (argument declaration)
{
function body
}
The membership label class-name with :: tells the compiler that the function
function-name belongs to the class class-name. That is, the scope of the function is
restricted to the class-name specified in the header line. The symbol :: is called the scope
resolution operator.
For instance, consider the member functions getdata( ) and putdata( ) as discussed
above. They may be coded as follows:
void student :: getdata()
{
cout << "Enter the register no.\n";
cin >> regno;
cout << "Enter the percentage \n";
cin >> percentage;
}
void student :: putdata()
{
cout << "Register No.: " << regno<< “\n”;
cout << "Percetage : " << percentage;
}
Friend functions:
The private members of a class cannot be accessed by non- member functions. But
there may be some situations where it is needed to access the private members of a class by
the non-member functions. This can be achieved by changing the access specifier or private

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 13


BCS306B An Overview of C++ Module 1

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";

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 14


BCS306B An Overview of C++ Module 1

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();
}

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 17


BCS306B An Overview of C++ Module 1

inline void large(int x, int y, int z)


{
int big; OUTPUT:
if(x > y) Enter 3 numbers
big = x; 7
else 2
big = y; 6
if(z > big) The largest number is 7
big = z;
cout<< "The largest number is "<<big;
}
Constructors and Destructors
A constructor is a special member function which is used to initialise the data
members automatically the moment the objects are created. This is known as automatic
initialisation of objects. It also provides another member function called the destructor that
destroys the objects when they are no longer required.
A constructor is declared and defined as follows:
class sample
{
int m, n;
public:
sample(void); //constructor declared
};
sample :: sample(void) //constructor defined outside class
{
m = n = 0;
}
OR
class sample
{
int m, n;
public:
sample(void); //constructor defined inside class
{
m = 0;
n = 0;
}
};
When a class contains a constructor like the one defined above, it is guaranteed that
an object created by the class will be initialized automatically. For example, the declaration
sample obj1; //object obj1 is created
Characteristics of a constructor:
• A constructor has the same name as that of class.
• A constructor is declared in the public section of a class definition.
• A constructor is invoked automatically as soon as the class object is created.
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 18
BCS306B An Overview of C++ Module 1

• 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
}

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 19


BCS306B An Overview of C++ Module 1

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;
}

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 20


BCS306B An Overview of C++ Module 1

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:

Object1 Object2 Object3


Automatic data Automatic data Automatic data

data1 data1 data1

data2 data2 data2 Static and Automatic


Member Variables
Static data

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.

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 24


BCS306B An Overview of C++ Module 1

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”;
}

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 25


BCS306B An Overview of C++ Module 1

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.

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 28


BCS306B An Overview of C++ Module 1

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();

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 29


BCS306B An Overview of C++ Module 1

cout << "T2 = "; //display T2


T2.display();
cout << "T3 = "; //display T3
T3.display();
getch();
}
Since the member function sum( ) is invoked by the object T3, with the object T1
and T2 as arguments, it can directly access the hours and minutes variables of T3. But, the
members of T1 and T2 can be accessed only by using the dot operator (like T1.hours and
T1.minutes). Therefore, inside the function sum( ), the variables hours and minutes refer
to T3, T1.hours and T1.minutes refer to T1 and T2.hours and T2.minutes refer to T2.
An object can also be passed as an argument to a non-member function. However
such functions can have access to the public member functions only through the objects
passed as arguments to it. These functions cannot have access to the private data members.
Returning Objects from Functions:
A function can not only receive objects as arguments but also can return them. The
flowing program illustrates how an object can be created (within a function) and returned to
another function.
Program to illustrate returning objects
class complex //x + iy form
{
float x; //real part
float y; //imaginary part
public:
void input(float real, float imag)
{
x = real;
y = imag;
}
friend complex sum(complex, complex)
void show(complex);
};
complex sum(complex c1, complex c2)
{
complex c3; //object c3 is created
c3.x = c1.x + c2.x;
c3.y = c1.y + c2.y;
return(c3); //return object c3
}
void complex :: show(complex c)
{
cout << c.x << " + i" << c.y << "\n";
}
void main()
{
Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 30
BCS306B An Overview of C++ Module 1

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

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 31


BCS306B An Overview of C++ Module 1

programs known as functions. structures are designed such that they


characterized the objects.
3) It is not possible to hide data for 3) Data can be hidden and can only be
allowing only restricted procedures to accessed outside via its associated
access them. member function.
4) New data and functions can be easily
4) All data should be declared at the added whenever necessary.
beginning of the program itself. 5) It is powerful tool that enable the
5) It’s difficult to design & deliver a programmers to solve the real world
solution that resembles the problem. A problems.
functions & data structure does not
cooperate to model the real world
situations.
6) Follows top-down approach in program 6) Follows bottom-up approach in program
design. design.
7) It does not provides defaults arguments 7) It provides defaults arguments
8) Memory management operators are not 8) Memory management operators are
available available (new and delete)
9) The key feature is structures and unions 9) The key feature is class

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

Dr.Shivashankara S, Dept. of CS & E, KR Pete Krishna Govt. Engg. College, KR Pet 32

You might also like