0% found this document useful (0 votes)
61 views35 pages

C++ Overview of C++: Object-Oriented Programming

C++ is a general purpose, compiled programming language that supports procedural, object-oriented, and generic programming. It was developed in 1979 as an enhancement to the C language and combines high-level and low-level language features. C++ fully supports object-oriented programming concepts like encapsulation, inheritance, and polymorphism. It is widely used to develop applications, operating systems, and embedded systems.

Uploaded by

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

C++ Overview of C++: Object-Oriented Programming

C++ is a general purpose, compiled programming language that supports procedural, object-oriented, and generic programming. It was developed in 1979 as an enhancement to the C language and combines high-level and low-level language features. C++ fully supports object-oriented programming concepts like encapsulation, inheritance, and polymorphism. It is widely used to develop applications, operating systems, and embedded systems.

Uploaded by

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

C++

OVERVIEW OF C++

 C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language


that supports procedural, object-oriented, and generic programming.
 C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-
level language features.
 C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an
enhancement to the C language and originally named C with Classes but later it was renamed C++ in
1983.
 C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

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.

THE ANSI STANDARD


 The ANSI standard is an attempt to ensure that C++ is portable; that code you write for Microsoft's
compiler will compile without errors, using a compiler on a Mac, UNIX, a Windows box, or an Alpha.
 The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers support
the ANSI standard.

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++

 Structure of a C+ + Program. Programs are a sequence of instructions or statements.


 These statements form the structure of a C++ program. C++ program structure is divided
into various sections, namely, headers, class definition, member functions definitions and main
function.

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.

Asm else new this

2
Auto enum operator throw

Bool explicit private true

Break export protected try

Case extern public typedef

Catch false register typeid

Char float reinterpret_cast typename

Class for return union

Const friend short unsigned

const_cast goto signed using

Continue if sizeof virtual

Default inline static void

Delete int static_cast volatile

Do long struct wchar_t

Double mutable switch while

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

Built-In 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

There are following arithmetic operators supported by C++ language −

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from A - B will give -10


the first

* Multiplies both operands A * B will give 200

/ Divides numerator by de- B / A will give 2


numerator

% Modulus Operator and B % A will give 0


remainder of after an integer
division

++ Increment operator, increases A++ will give 11


integer value by one

-- Decrement operator, A-- will give 9


decreases integer value by one

Relational Operators
There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then −


Show Examples

6
Operator Description Example

== Checks if the values of (A == B) is not true.


two operands are equal
or not, if yes then
condition becomes true.

!= Checks if the values of (A != B) is true.


two operands are equal
or not, if values are not
equal then condition
becomes true.

> Checks if the value of (A > B) is not true.


left operand is greater
than the value of right
operand, if yes then
condition becomes true.

< Checks if the value of (A < B) is true.


left operand is less than
the value of right
operand, if yes then
condition becomes true.

>= Checks if the value of (A >= B) is not true.


left operand is greater
than or equal to the
value of right operand, if
yes then condition
becomes true.

<= Checks if the value of (A <= B) is true.


left operand is less than
or equal to the value of
right operand, if yes
then condition becomes
true.

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

Operator Description Example

&& Called Logical AND (A && B) is false.


operator. If both the
operands are non-
zero, then condition
becomes true.

|| Called Logical OR (A || B) is true.


Operator. If any of
the two operands is
non-zero, then
condition becomes
true.

! Called Logical NOT !(A && B) is true.


Operator. Use to
reverses the logical
state of its operand. If
a condition is true,
then Logical NOT
operator will make
false.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −

p Q p&q p|q p^q

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&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~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

Operator Description Example

& Binary AND


Operator copies a bit
(A & B) will give 12
to the result if it
which is 0000 1100
exists in both
operands.

| Binary OR Operator (A | B) will give 61


copies a bit if it exists which is 0011 1101
in either operand.

^ 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.

~ Binary Ones (~A ) will give -61


Complement which is 1100 0011
Operator is unary and in 2's complement
has the effect of form due to a signed
'flipping' bits. binary number.

<< Binary Left Shift


Operator. The left
operands value is
A << 2 will give 240
moved left by the
which is 1111 0000
number of bits
specified by the right
operand.

>> Binary Right Shift


Operator. The left
operands value is
A >> 2 will give 15
moved right by the
which is 0000 1111
number of bits
specified by the right
operand.

Assignment Operators
There are following assignment operators supported by C++ language −

Show Examples

Operator Description Example

= Simple assignment C = A + B will


operator, Assigns assign value of A +

10
values from right side B into C
operands to left side
operand.

+= Add AND assignment


operator, It adds right C += A is
operand to the left equivalent to C =
operand and assign the C + A
result to left 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.

<<= Left shift AND C <<= 2 is same as


assignment operator. C = C << 2

>>= Right shift AND C >>= 2 is same as


assignment operator. C = C >> 2

&= Bitwise AND C &= 2 is same as


assignment operator. C=C&2

^= 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.

Sr.No Operator & Description

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.

4 . (dot) and -> (arrow)


Member operators are used to reference
individual members of classes, structures, and
unions.

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.

Operators Precedence in C++

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

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & Right to left


sizeof

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

14
Assignment = += -= *= /= %=>>= <<= Right to left
&= ^= |=

Comma , Left to right

FUNCTIONS

A function is a group of statements that together perform a task. Every C++


program has at least one function, which is main(), and all the most trivial
programs can define additional 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.

A function is known with various names like a method or a sub-routine or a


procedure etc.

Defining a Function
The general form of a C++ function definition is as follows −

return_type function_name( parameter list ) {


body of the function

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.

Function Overloading in C++


 You can have multiple definitions for the same function name in the same scope.
 The definition of the function must differ from each other by the types and/or the
number of arguments in the argument list.
 You cannot overload function declarations that differ only by return type.
 Following is the example where same function print() is being used to print different
data types −
#include <iostream>

using namespace std;

16
class printData {

public:

void print(int i) {

cout << "Printing int: " << i << endl;

void print(double f) {

cout << "Printing float: " << f << endl;

void print(char* c) {

cout << "Printing character: " << c << endl;

};

int main(void) {

printData pd;

// Call print to print integer

pd.print(5);

// Call print to print float

pd.print(500.263);

// Call print to print character

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++

Operators Overloading in 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&);

CLASSES AND OBJECTS


The main purpose of C++ programming is to add object orientation to the C programming language and
classes are the central feature of C++ that supports object-oriented programming and are often called
user-defined types.
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package. The data and functions within a class are called members
of the class.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but
it does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed
by a pair of curly braces. A class definition must be followed either by a semicolon or a list of
declarations. For example, we defined the Box data type using the keyword class as follows −

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>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box

double height; // Height of a box


};

int main() {
Box Box1; // Declare Box1 of type Box

Box Box2; // Declare Box2 of type Box


double volume = 0.0; // Store the volume of a box here

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

cout << "Volume of Box1 : " << volume <<endl;

// 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 −

Volume of Box1 : 210


Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed directly using direct
member access operator (.). We will learn how private and protected members can be accessed.


ARRAY OF OBJECTS
 The array of type class contains the objects of the class as its individual elements.

 Thus, an array of a class type is also known as an array of objects.

 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.

Syntax for Array of object

class class-name
{
datatype var1;
datatype var2;
----------

20
datatype varN;

method1();
method2();
----------
methodN();
};

class-name obj[ size ];

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>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor

private:

double length;

};

// Member functions definitions including constructor

21
Line::Line(void) {

cout << "Object is being created" << endl;

void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

cout << "Length of line : " << line.getLength() <<endl;

return 0;

When the above code is compiled and executed, it produces the following result −

Object is being created


Length of line : 6
Parameterized Constructor
A default constructor does not have any parameter, but if you need, a constructor can have parameters.
This helps you to assign initial value to an object at the time of its creation as shown in the following
example −

The Class Destructor


22
A destructor is a special member function of a class that is executed whenever an object of it's class
goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a
value nor can it take any parameters. Destructor can be very useful for releasing resources before coming
out of the program like closing files, releasing memories etc.
Following example explains the concept of destructor −

#include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor declaration

~Line(); // This is the destructor: declaration

private:

double length;

};

// Member functions definitions including constructor

Line::Line(void) {

cout << "Object is being created" << endl;

Line::~Line(void) {

cout << "Object is being deleted" << endl;

23
void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

cout << "Length of line : " << line.getLength() <<endl;

return 0;

When the above code is compiled and executed, it produces the following result −

Object is being created


Length of line : 6
Object is being deleted

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.

OPERATOR OVERLOADING USING UNARY OPERATOR

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>

using namespace std;

class Distance {

private:

int feet; // 0 to infinite

int inches; // 0 to 12

public:

// required constructors

Distance() {

feet = 0;

inches = 0;

Distance(int f, int i) {

feet = f;

inches = i;

// method to display distance

void displayDistance() {

cout << "F: " << feet << " I:" << inches <<endl;

25
}

// overloaded minus (-) operator

Distance operator- () {

feet = -feet;

inches = -inches;

return Distance(feet, inches);

};

int main() {

Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation

D1.displayDistance(); // display D1

-D2; // apply negation

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.

MANIPULATION OF STRINGS USING FRIENDS IN C++


 A string is a sequence of character. As you know that C++ does not support built-instring type,
you have used earlier those null character based terminated array of characters to store
and manipulate strings.

 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 Only existing operators can be overloaded. New operators cannot be overloaded.

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 We cannot use “friend” functions to overload certain operators.However, member


function can be used to overload them. Friend Functions can not be used with
assignment operator(=), function call operator(()), subscripting operator([]), class
member access operator(->) etc.

o Unary operators, overloaded by means of a member function, take no explicit arguments


and return no explicit values, but, those overloaded by means of a friend function, take
one reference argument (the object of the relevent class).

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 −

class derived-class: access-specifier base-class


Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows −

#include <iostream>

using namespace std;

// 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

class Rectangle: public Shape {

public:

int getArea() {

return (width * height);

};

int main(void) {

Rectangle Rect;

Rect.setWidth(5);

Rect.setHeight(7);

// Print the area of the object.

cout << "Total area: " << Rect.getArea() << endl;

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 −

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

A derived class inherits all base class methods with the following exceptions −

 Constructors, destructors and copy constructors of the base class.


 Overloaded operators of the base class.
 The friend functions of the base class.

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 −

class derived-class: access baseA, access baseB....


Where access is one of public, protected, or private and would be given for every base class and they
will be separated by comma.
TYPES OF INHERITANCES
C++ supports six types of inheritance as follows:

 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

You might also like