C++ Overview of C++: Object-Oriented Programming
C++ Overview of C++: Object-Oriented Programming
OVERVIEW OF C++
OBJECT-ORIENTED PROGRAMMING
C++ fully supports object-oriented programming, including the four pillars of object-oriented development −
Encapsulation
Data hiding
Inheritance
Polymorphism
STANDARD LIBRARIES
Standard C++ consists of three important parts −
The core language giving all the building blocks including variables, data types and literals, etc.
The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.
The Standard Template Library (STL) giving a rich set of methods manipulating data structures, etc.
USE OF C++
C++ is used by hundreds of thousands of programmers in essentially every application domain.
C++ is being highly used to write device drivers and other software that rely on direct manipulation of
hardware under realtime constraints.
C++ is widely used for teaching and research because it is clean enough for successful teaching of basic
concepts.
Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++
because the primary user interfaces of these systems are written in C++.
1
APPLICATIONS OF C++
C++ allows us to create hierarchy related objects.
C++ is able to map the real world problems.
It is easily expandable and maintainable.
It is a general purpose language which will replace C.
STRUCTURE OF C++
TOKENS
A programming token is the basic component of source code.
Characters are categorized as one of five classes of tokens that describe their functions
(constants, identifiers, operators, reserved words, and separators) in accordance with the rules of
the programming language.
C++ has following tokens
Keywords
Identifiers
Constants
Strings
Operators
KEYWORDS
C++ Keywords
The following list shows the reserved words in C++. These reserved words may not be used as
constant or variable or any other identifier names.
2
Auto enum operator throw
dynamic_cast namespace
IDENTIFIERS
3
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined
item.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive
programming language.
Thus, Manpowerand manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
CONSTANTS
Constants refer to fixed values that do not change during the execution of a
Program.
In C++ language constants are of two types:
Numeric
Non numeric constant(character constant)
Example
1234 //decimal integer
12.34 //floating point integer
DATA TYPES
A data type determines the type and the operations that can be performed on the data.
C++ provides various data types and each data type is represented differently within the computer's
memory.
The various data types provided by C++ are built-in data types, derived data types and user-defined data
types
4
The basic (fundamental) data types provided by c++ are integral, floating point and void data type. Among these
data types, the integral and floating-point data types can be preceded by several type modifiers. These modifiers
(also known as type qualifiers) are the keywords that alter either size or range or both of the data types. The various
modifiers are short, long, signed and unsigned. By default the modifier is signed.
In addition to these basic data types, ANSI C++ has introduced two more data types namely, bool and wchar_t.
Integral Data Type: The integral data type is used to store integers and includes char (character) and int (integer)
data types.
Char: Characters refer to the alphabet, numbers and other characters (such as {, @, #, etc.) defined in the ASCII
character set. In C++, the char data type is also treated as an integer data type as the characters are internally stored
as integers that range in value from -128 to 127. The char data type occupies 1 byte of memory (that is, it holds only
one character at a time).
The modifiers that can precede char are signed and unsigned. The various character data types with their size and
range are listed in Table
Derived Data Types: Data types that are derived from the built-in data types are known as
derived data types. The various derived data types provided by C++ are arrays, junctions,
references and pointers.
OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
5
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.
Arithmetic Operators
Show Examples
Relational Operators
There are following relational operators supported by C++ language
6
Operator Description Example
Logical Operators
There are following logical operators supported by C++ language.
7
Assume variable A holds 1 and variable B holds 0, then −
Show Examples
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −
0 0 0 0 0
8
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60
and variable B holds 13, then −
Show Examples
^ Binary XOR
(A ^ B) will give 49
Operator copies the
9
bit if it is set in one which is 0011 0001
operand but not both.
Assignment Operators
There are following assignment operators supported by C++ language −
Show Examples
10
values from right side B into C
operands to left side
operand.
-= Subtract AND
assignment operator, It
C -= A is
subtracts right operand
equivalent to C =
from the left operand
C-A
and assign the result to
left operand.
*= Multiply AND
assignment operator, It
C *= A is
multiplies right
equivalent to C =
operand with the left
C*A
operand and assign the
result to left operand.
/= Divide AND
assignment operator, It
C /= A is
divides left operand
equivalent to C =
with the right operand
C/A
and assign the result to
left operand.
%= Modulus AND C %= A is
assignment operator, It equivalent to C =
11
takes modulus using C%A
two operands and
assign the result to left
operand.
^= Bitwise exclusive OR
C ^= 2 is same as
and assignment
C=C^2
operator.
|= Bitwise inclusive OR
C |= 2 is same as C
and assignment
=C|2
operator.
Misc Operators
The following table lists some other operators that C++ supports.
1 Sizeof
sizeof operator returns the size of a variable.
For example, sizeof(a), where ‘a’ is integer, and
will return 4.
12
2 Condition ? X : Y
Conditional operator (?). If Condition is true
then it returns value of X otherwise returns value
of Y.
3 ,
Comma operator causes a sequence of
operations to be performed. The value of the
entire comma expression is the value of the last
expression of the comma-separated list.
5 Cast
Casting operators convert one data type to
another. For example, int(2.2000) would return
2.
6 &
Pointer operator & returns the address of a
variable. For example &a; will give actual
address of the variable.
7 *
Pointer operator * is pointer to a variable. For
example *var; will pointer to a variable var.
13
Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
14
Assignment = += -= *= /= %=>>= <<= Right to left
&= ^= |=
FUNCTIONS
You can divide up your code into separate functions. How you divide up your
code among different functions is up to you, but logically the division usually is
such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type,
and parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program
can call. For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and many
more functions.
Defining a Function
The general form of a C++ function definition is as follows −
15
}
A C++ function definition consists of a function header and a function body. Here
are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
Function Body − The function body contains a collection of statements that define what the function does.
FUNCTION OVERLOADING
C++ allows you to specify more than one definition for a function name or an operator in the
same scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a previously
declared declaration in the same scope, except that both declarations have different arguments
and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use, by comparing the argument types you have used to call the
function or operator with the parameter types specified in the definitions. The process of
selecting the most appropriate overloaded function or operator is called overload resolution.
16
class printData {
public:
void print(int i) {
void print(double f) {
void print(char* c) {
};
int main(void) {
printData pd;
pd.print(5);
pd.print(500.263);
pd.print("Hello C++");
return 0;
When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
17
You can redefine or overload most of the built-in operators available in C++. Thus, a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed
by the symbol for the operator being defined.
Like any other function, an overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final
Box object.
Most overloaded operators may be defined as ordinary non-member functions or as class
member functions.
In case we define above function as non-member function of a class then we would have
to pass two arguments for each operand as follows
Box operator+(const Box&, const Box&);
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follows it. A public
member can be accessed from outside the class anywhere within the scope of the class object. You can
also specify the members of a class as private or protected which we will discuss in a sub-section.
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created from a class. We declare
objects of a class with exactly the same sort of declaration that we declare variables of basic types.
Following statements declare two objects of class Box −
18
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct member access operator
(.). Let us try the following example to make the things clear −
#include <iostream>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
int main() {
Box Box1; // Declare Box1 of type Box
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
19
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
When the above code is compiled and executed, it produces the following result −
–
ARRAY OF OBJECTS
The array of type class contains the objects of the class as its individual elements.
An array of objects is declared in the same way as an array of any built-in data type.
An object of class represents a single record in memory, if we want more than one record of class type,
we have to create an array of class or object. As we know, an array is a collection of similar type,
therefore an array can be a collection of class type.
class class-name
{
datatype var1;
datatype var2;
----------
20
datatype varN;
method1();
method2();
----------
methodN();
};
CONSTRUCTORS
A class constructor is a special member function of a class that is executed whenever we create new
objects of that class.
A constructor will have exact same name as the class and it does not have any return type at all, not even
void. Constructors can be very useful for setting initial values for certain member variables.
Following example explains the concept of constructor −
#include <iostream>
class Line {
public:
private:
double length;
};
21
Line::Line(void) {
length = len;
return length;
int main() {
Line line;
line.setLength(6.0);
return 0;
When the above code is compiled and executed, it produces the following result −
#include <iostream>
class Line {
public:
private:
double length;
};
Line::Line(void) {
Line::~Line(void) {
23
void Line::setLength( double len ) {
length = len;
return length;
int main() {
Line line;
line.setLength(6.0);
return 0;
When the above code is compiled and executed, it produces the following result −
COPY CONSTRUCTORS
A variable is declared which is initialized from another object, eg, Person q("Mickey");
A value parameter is initialized from its corresponding argument. ...
An object is returned by a function.
The unary operators operate on a single operand and following are the examples of Unary operators −
24
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears
on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well
like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage.
#include <iostream>
class Distance {
private:
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
Distance(int f, int i) {
feet = f;
inches = i;
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
25
}
Distance operator- () {
feet = -feet;
inches = -inches;
};
int main() {
D1.displayDistance(); // display D1
D2.displayDistance(); // display D2
return 0;
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11
OVERLOADING USING BINARY OPERATORS
The binary operators take two arguments and following are the examples of Binary operators.
You use binary operators very frequently like addition (+) operator, subtraction (-) operator and
division (/) operator.
26
Following example explains how addition (+) operator can be overloaded. Similar way, you can
overload subtraction (-) and division (/) operators.
These strings are termed as CStrings. It often becomes inefficient performing operations on
C strings.
RULE FOR OVERLOADING OPERATORS
Every programmer knows the concept of operation overloading in C++. Although it looks simple to
redefine the operators in operator overloading, there are certain restrictions and limitation in overloading
the operators. Some of them are listed below:
o The overloaded operator must have at least one operand that is of user defined type.
o We cannot change the basic meaning of an operator. That is to say, We cannot redefine
the plus(+) operator to subtract one value from the other.
o Overloaded operators follow the syntax rules of the original operators. They cannot be
overridden.
o There are some operators that cannot be overloaded like size of operator(sizeof),
membership operator(.), pointer to member operator(.*), scope resolution operator(::),
conditional operators(?:) etc
o Binary operators overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.
27
o When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
o Binary arithmetic operators such as +,-,* and / must explicitly return a value. They must
not attempt to change their own arguments.
INHERITANCE
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance
allows us to define a class in terms of another class, which makes it easier to create and maintain an
application. This also provides an opportunity to reuse the code functionality and fast implementation
time.
When creating a class, instead of writing completely new data members and member functions, the
programmer can designate that the new class should inherit the members of an existing class. This
existing class is called the baseclass, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A
mammal hence dog IS-A animal as well and so on.
Base and Derived Classes
A class can be derived from more than one classes, which means it can inherit data and functions from
multiple base classes. To define a derived class, we use a class derivation list to specify the base
class(es). A class derivation list names one or more base classes and has the form −
#include <iostream>
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
28
void setHeight(int h) {
height = h;
protected:
int width;
int height;
};
// Derived class
public:
int getArea() {
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
29
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Access Control and Inheritance
A derived class can access all the non-private members of its base class. Thus base-class members that
should not be accessible to the member functions of derived classes should be declared private in the
base class.
We can summarize the different access types according to - who can access them in the following way −
A derived class inherits all base class methods with the following exceptions −
Type of Inheritance
When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used. While using
different type of inheritance, following rules are applied −
Public Inheritance − When deriving a class from a public base class, public members of the
base class become public members of the derived class and protected members of the base
class become protected members of the derived class. A base class's privatemembers are never
accessible directly from a derived class, but can be accessed through calls to
the public and protected members of the base class.
Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class become protected members of the
derived class.
30
Private Inheritance − When deriving from a private base class, public and protected members
of the base class become privatemembers of the derived class.
Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended syntax −
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Heirarchical Inheritance
Hybrid Inheritance
Multipath Inheritance
Single Inheritance
A derived class with only one base class is called single inheritance.
Multilevel Inheritance
A derived class with one base class and that base class is a derived class of another is called multilevel
inheritance.
31
Multiple Inheritance
A derived class with multiple base class is called multiple inheritance.
Heirarchical Inheritance
Multiple derived classes with same base class is called hierarchical
inheritance.
32
Hybrid Inheritance
Combination of multiple and hierarchical inheritance is called hybrid inheritance.
Multipath Inheritance
A derived class with two base classes and these two base classes have one common base class is called multipath
inheritance.
33
VIRTUAL BASECLASS
Virtual base class is used in situation where a derived have multiple copies of base class. Consider the following
figure:
34
ABSTRACT AND MEMBER CLASS
An interface describes the behavior or capabilities of a C++ class without committing to a particular
implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract classes should not be
confused with data abstraction which is a concept of keeping implementation details separate from
associated data.
A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual
function is specified by placing "= 0" in its declaration as follows −
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class
from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves
only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions,
which means that it supports the interface declared by the ABC. Failure to override a pure virtual
function in a derived class, then attempting to instantiate objects of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.
35