0% found this document useful (0 votes)
15 views

c++ Notes

The document provides an overview of Object-Oriented Programming (OOP) principles, including encapsulation, data hiding, classes, and objects, emphasizing the importance of data over procedures. It also covers basic data types in C++, variable definitions, functions, and parameter passing methods, highlighting the differences between OOP and Procedure-Oriented Programming (POP). Additionally, it discusses polymorphism, protection levels in classes, and includes code examples demonstrating various concepts.

Uploaded by

drzubair
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)
15 views

c++ Notes

The document provides an overview of Object-Oriented Programming (OOP) principles, including encapsulation, data hiding, classes, and objects, emphasizing the importance of data over procedures. It also covers basic data types in C++, variable definitions, functions, and parameter passing methods, highlighting the differences between OOP and Procedure-Oriented Programming (POP). Additionally, it discusses polymorphism, protection levels in classes, and includes code examples demonstrating various concepts.

Uploaded by

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

Aurora’s Degree College [C++ Notes] Dept.

of Computer Science

OOPS AND ITS CHARACTERISTICS

Programs and data are two basic elements of any computation in conventional method.
Data is defined as a global and accessible to all the functions of a program. Without any
restrictions it leads to reduce data security and integrity. Since the data is available to all
the functions and any function can change any data.

Object oriented programming emphasis more on the data. In object oriented


programming data is encapsulated with the associated functions and this capsule is
called an “object”.

If we want to modify or access the data in an object then we should know exactly what
member function interacts with it. No other functions can access the data object oriented
programming facilities creation of new data types this feature of oops leads to
extensibility of the language.

NOTE:
1 The most important and basic concept of oops is the concept of the class. In class
we bundle the data and functions together that operate on the data into a single
unit called class. A class is a specification of a data entity. This data entity is
called an object is an instant of a class.
2 Defining the class doesn‟t perform any memory allocation. When an object is
created then only memory will be allocated. Objects interact with one another
through the member function.
3 Another most powerful features of powerful language that supports oops are
“encapsulation and data hiding”.
Encapsulation is the ability to bundle together data and method into a single unit
called an object. Data hiding is the inability to access an object data by means other
than by using member functions.

OOPS METHODOLOGY

1 The objects are autonomous entities and share their responsibilities only by
executing methods relevant to the received messages.
2 Each object lends itself to greater modularity.
3 Co-operation among different objects to achieve the system operation is turn
through exchanges of messages.
4 The independence of each object eases development and maintenance of the
program.
5 Information hiding and data abstraction increase reliability.
6 Object oriented design involves the identification and implementation of different
classes, objects and their behaviors.

Page 1 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

DATA TYPES
Basic data types in C++:

DATA TYPES RANGE FROM TO BYTES


1 char -128 to 127 1
2 unsigned char 0 to 255 1
3 short -32768 to32767 2
4 unsigned short 0 to 65536 2
5 int -32768 to 32767 2
6 unsigned int 0 to 65536 2
7 long int -21474836482 to
21474836481 4
8 signed long int 0 to 4294967296 4
9 float -3.4*10-38 to 3.4*1038 4
10 double -1.7*10-308 to 1.7*10308 8
11long double 3.4*10-4932 to 1.1*104932 16
12void 0

VARIABLES

A variable is an entity whose values can be changed during program execution


and is known to the program by a name.
A variable definition associates a memory location to the variable name. Any
variable can store or hold one value at a time, during the program execution and its
value changes from time to time.

FUNCTIONS

Functions are of two types-


Inbuilt functions
User defined function
Functions are sub-modules or sub-programs which needs to be created once and can be
called n number of times. A specific task to be achieved can be placed in sub-modules.

FUNCTION PROTOTYPE

It describes function interface to compiler by giving details of functions, types of


arguments and also type of return values. In c++ declaring a function prototype is a
complete statement and is to be terminated with semicolon.

SYNTAX:

Returntype functionname (argument list[if any]) ;

CALLING OR ACCESSING FUNCTION


A function can be called or invoked or executed by function name followed by
parameters. A function once created can be called n number of times by specifying its
name and required parameters.

RETURN
Value of variable is returned to a calling program by using return statement. Return
statement can return one value at a time. Multiple variable return is possible by using
pass by reference

BREAK
Break statement enables a program to skip over part of program. It causes an exit from
loop. Break statement terminates smallest enclosing while, do-while, for, switch etc.

Page 2 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

CONTINUE
Continue statement takes control back to start of loop. Break statement causes loop to
terminate and reaches at the bottom of the loop. When it is necessary to go back to loop
if some unexpected arises inside the loop, in this case continue statement is very useful.

EXIT
A break statement causes break from loop, the same can be achieved by a library
function of c++, that is exit function. It is used to terminate the program as soon as it is
encountered. exit (0) causes program to terminate no matter where it exists in listing.
Value zero in exist is normally used for a successful termination.

INLINE FUNCTION
All calls to a function cause some code to be executed. Function body need not be
duplicated in memory. This saves memory space because function is stored at only one
place; still some extra time is consumed in function calling. Also some space is used to
invoke function. Passing parameters to function allocates storage for its local variables
To save execution time particularly in short functions, method is to put code in
the function body directly inline with code in calling program. This means each time
there is a function call in source file; the actual code from function code is inserted,
instead of a jump to a function.
Inline functions can be written like a normal function in source file. The concept is
achieved by specifying the function to be inline by using inline keyword. This will inform
compiler to replace each call to the function by code for the function.

/*STRING CONCATENATION*/
#include<iostream.h>
#include<string.h>
#include<stdio.h>
void main()
{
char st1[80],st2[80];
cout<<”enter first name\n”;
gets(st1);
cout<<”enter second name\n”;
gets(st2);
cout<<”string1=”<<st1<<endl;
cout<<”string2=”<<st2<<endl;
strcat(st1,st2);
cout<<”after concatenation”;
cout<<st1;
getch();
}

/*refer string length and string comparison from notes*/

MACROS AND INLINE FUNCTIONS


Inline function:

#include<iostream.h>
inline double square (double n)
{
return(n*n);
}
void main()
{double a=10.6;
double b;
clrscr();

Page 3 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

cout<<”value of a=”<<a;
b=square(a++);
cout<<”value of a*a”<<b<<endl;
getch();
}

MACRO FUNCTION

#define square(x)
void main()
{
double a=10.6;
double b;
cout<<”enter value of a”<<a<<endl;
b=square(a++);
cout<<”enter value of a*a”<<b<<endl;
}

Parameter passing methods supported in C++

Parameter passing methods in C++ are the way in which the parameters are transmitted
to and from called subprograms called functions. Formal parameters are characterized
by one of the three distinct semantic models.

1. They can receive data from the corresponding actual parameters.


2. They can transmit data to actual parameters.
3. They can do both (IN and OUT)

These three models are called IN mode, OUT mode and INOUT mode respectively.
C++ supports pass by value and pass by reference for passing parameters.

Pass by value: When a parameter is passed by a values, the value of an actual


parameter is used to initialize the corresponding formal parameter which then acts as a
local variable in the subprogram. It is implemented usually by actual data transfer. It
could be implemented by transferring the access part to the value of the actual
parameter in the caller program.
The corresponding actual parameters need not be constants. They are enforced to
be constant and if required. This allows pointer parameter to provide the efficiency of
pass by reference with semantics of pass by value.

Pass by reference: Pass by reference is an implementation model for IN-OUT


parameter rather than transmitting data values back. This method passes an access path
i.e. an address to the called subprogram. The called subprogram has direct access to the
cell where the data venue is stored and hence can make modifications to it.
The actual parameters are shared with the called subprograms. C++ does this by
including a special pointer type called Reference Type i.e. often used for parameters.

Passing entire array as a function argument: It is also possible to pass an entire


array as an argument to a function. Formal parameters is a kind of place holders that
occurs in a function definitions and i.e. filled in with an argument when the function is
called.
When the function is called each argument is plugged in for its corresponding
formal parameters and then the code in the function body.

Page 4 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

A function can have a formal parameter for an entire array so that the function is
called the argument i.e plugged in for this formal parameters in an entire array.
A formal parameter for an entire array is neither a call by value parameter nor a
call by reference parameter. It is a new kind of formal parameter refer to as an array
parameter.
Eg. int sum(a[],size)
The formal parameter int sum(a[],size) is an array parameter.the square brackets with
no index are used to indicate an array parameters .An array is not a quiet call by
reference parameter but for most practical purposes it very much behaves like a call by
reference parameter.

WAC++ PROGRAM USING RECURSION TO FIND POWER OF NUMBER


#include<iostream.h>
#include<stdlib.h>
int power(int,int);
void main()
{
int n;
for(n=0;n<4;n++)
{
cout<<”3 to the power of”<<n<<”is”<<power (3,n)<<endl;
}
getch();
}
int power(int x,int n)
{
if(n<0)
{
cout<<”invalid number”;
exit(1);
}
if(n>0)
return (power(x,n-1)*x);
else
return(1);
}

FUNCTIONS WITH DEFAULT ARGUMENT:

A default argument is a value that is used automatically as the function argument when
we omit the actual argument from the function call. Normal function calls check for the
arguments. The compiler look at the function prototype to find out number of arguments
and type of argument list the function uses.

SYNTAX:
Returntype functionname (int varname default value);

E.g. Int sum (int a=10, int b=10);

When we use a function with argument lists, we can add default from right to left. We
can provide a default value for a particular argument unless we provide default values
for all the arguments to its right.

Page 5 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

E.g. Void func(int x=10; int y=20; int z); //invalid

void func(int x=10;int y=20;int z=30); //valid

If above is the function prototype then the following statements are valid,

func (10) func(10, 20,30);


func(10,500) func(10, 500,30);

DIFFERENCE BETWEEN OOPS &


PROCEDURE ORIENTED PROGRAMMING(POP):

OOP:
1. It emphasizes data rather than procedure.
2. Programs are divided into what are called objects.
3. Data structures are designed such that they categorized the object.
4. Functions that operate on data of an object are tied together in data
structure.
5. Data is hidden and cannot be accessed by external function.
6. It follows bottom top approach in program design.
7. Objects may communicate with each other through functions.
8. New data and function can be added easily when ever needed.
9. It supports the concept of reversibility.

POP:
1. It emphasizes more on (algorithm) doing things.
2. Large program is divided into small program called function.
3. Most of the function shares a global data.
4. Data moves openly around the system from function to function.
5. Function transforms data from one form to another.
6. Development becomes complex as the complexity of the program increases.
7. It follow top down approach in program design.
8. Difficult to add new data functions, entire program need to be re-developed.

CLASSES:
Class is a user defined data type. The entire set of data and code of an object can be
made user defined data type with the help of a class. Objects are variable of class.
We can create any number of objects once a class has been defined. A class is a
collection of objects of similar type. Classes are user defined data types and behave
like inbuilt types of programming language.
Class ----- > i) User defined data type.
ii) Abstract Data Type (ADT)

Class provides data encapsulation, data security and data abstraction.

Objects: Objects are basic run time entity in an object oriented system. Objects are
also known as instance of a class. They may represent a person, a place, a bank
account, a table of data or any item that the program must handle. They may also
represent user defined data type such as vectors, time and lists. Programming
problem is an analyst in term of object and nature of communication between them.
Program object should be chosen such that they match closely with the real world
objects.

Page 6 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

When a program is executed, the object interact by sending message to one another
which is also known as message passing, objects can interact without having to know
details of each other data or code. It is sufficient to know the type of message
accepted and the type of response returns by the object.

Data Abstraction and Encapsulation:

The wrapping up of or merging of data members and member functions in a single


unit (class) is called 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 have wrapped in the class can access it. This function provides the interface
between the objects data and the program. The insulation of a data from the direct
access by the program is called Data Hiding.

Protection levels in classes

C++ allows three levels of protection of attributes in classes. These are public, protected
and private.

These levels restrict access to identifiers, they do not hide them. Name conflicts with
protected attributes occur as if they were not protected at all.

Private :
A private attribute can only be used by functions within that class or by friend
functions of that class. It is not accessible to code outside the class, nor to code
in a sub- class function. This is the most restrictive level of access.

Protected :
A protected attribute cannot be accessed from outside the class, only within
functions of its class or classes derived from it publicly or protectedly or within
friend functions of these classes. It is kept in the family. This is important when
using inheritance to define layered software designs, since making an atribute
private can seal it above a layer, but protecting an attribute leaves it open to use
in a controlled way.
Public :
Public attributes are not hidden at all and can be through out the program outside
the class.

Page 7 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

Polymorphism

Polymorphism is of two types


(1) Compile Time Polymorphism (Static Polymorphism)
(2) Run Time Polymorphism (Dynamic polymorphism)

Polymorphism

Compile Time Polymorphism Run Time Polymorphism


or Static Polymorphism or Dynamic Polymorphism

(Early Binding) (Late Binding)

Function overloading
Virtual Functions

Operator overloading

Polymorphism means ability to take more than one form. An operation may exhibit
different behavior in different instances. The behavior depends upon the type of data
used in operation.
E.g. For two numbers the operation will generate sum.
Sum (1, 2)
If the operators are string then the operation would produce a third string by
concatenation.
Sum („A‟, „B‟)
A single function name can be used to handle different number and different types of
arguments.
NOTE:
polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. Polymorphism is extensively used in
implementing inheritance.

Polymorphism is of two types-


(1) compile time [early binding]
(2) run time [late binding]

The objects are bound to its function call at the compile time is known as compile time
polymorphism.
The function is linked with a particular class much later after compilation. This process is
called as late binding. It is also known as run time polymorphism.

Page 8 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

Function Overloading:

Function that share the same name are said to be overloaded and the process is referred
to as function overloading. The minimum requirement for function overloading is that,
the functions must differ in type, number or sequence of parameters. Two functions of
the same name cannot be overloaded if their return types alone are different.

void display(int); //error during compilation


int display(int); //error during compilation
void display(); //no error during compilation
void display(int); //no error during compilation
void display(int,float); //no error during compilation

CONSTRUCTORS:

Constructors are a special member function that invokes or executes automatically at the
time of object creation.
A member function with the same name as of that of class is a constructor. It is called
constructor because it constructs the value of data members of the class.
It is used to initialize objects of class type with legal initial values. It has to be defined in
the public section.

Types of constructors:
1. Default constructor or void constructors
2. Parameterized constructor
3. Copy constructors
4. Dynamic constructors
5. Constructor with default arguments
6. Over loaded constructors

Rules for Constructor Declaration:


1. Name of the constructor must match the name of its class.
2. A constructor never returns any value, not even void. Therefore it can be
declared with no return type.
3. A constructor may not be static or virtual function.
4. A constructor should have public/protected access.
5. If in a class we do not declare a constructor, then c++ declares default
constructor for that class.
6. A class can have multiple constructors.
7. A constructor with no parameter is called void constructor or default constructor.
8. A constructor with parameter is called parameterized constructor.
9. When the constructor is parameterized then we must provide appropriate
arguments for the constructors.
10. A constructor with parameter of class type is called copy constructors.
11. Constructors cannot be inherited, though a derived class can call base call
constructor.
12. Like others c++ function they can have default arguments.
13. We cannot refer to their addresses.
14. An object with a constructor (destructor) cannot be used as a member of a union.
15. They make implicit calls to the operators (new and delete) when memory
allocation is required.
16. When a constructor is declared for a class initialization of class objects become
mandatory.

Page 9 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

DESTRUCTORS:

1. A destructor is a complimentary to a constructor. it is used for de-initialization.


2. A destructor invokes automatically or can be called when the object goes out of
scope or when it is destroyed explicitly using delete option.
3. When declaring a destructor it should be a class name prefixed by ~.
4. Destructors cannot take arguments or specifies or returns value.
5. A class cannot have more than one destructor.

PASSING OBJECTS AS PARAMETER:

Eg: A C++ program to demonstrate Passing object as parameter

Class time
{
Private:
int hours;
int minutes;
Public:
void gettime(int,int);
void puttime();
void addtime(time t1,time t2);
};

void time::gettime(int a,int b)


{
hours=a;
mins=b;
}

void time::puttime()
{
cout<<”\n hours=”<<hours<<endl;
cout<<”\n mins=”<<mins;
}

void time:: addtime(time t1,time t2)


{
mins=t1.mins+t2.mins;
hours=min/60;
mins=mins%60;
hours=hours+t1.hours+t2.hours;
}
void main()
{
time t1,t2,t3;
t1.gettime(3,50);
t2.gettime(4,20);
t3.addtime(t1,t2);
cout<<”\n forenoon=”<<endl;
t1.puttime():
cout<<”\n afternoon”<<endl;
t2.puttime();
cout<<”total working hours”<<endl;
t3.puttime();
getch();
}

Page 10 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

Static data members and member functions:

Static data types can be accessed without instantiation of the class in C++. This is
applicable for static functions also.

Objects of a class maintain their own copy of data members. If all objects of a class have
to access the same copy of any variable then we declare that variable as static variable.
A static variable doesn‟t refreshes (re-initializes) every time when an object is created.

Static Variable Syntax:

static <data type> <variable name>;

Static functions are member functions that access only the static data of a class.
Static functions can be accessed either through an object, or directly, without creating
an instance of the class using „::‟ operator.
Declaration of static member function within the class can be done by prefixing keyword
static in the function declaration.

The differences between a static member function and non-static member functions are
as follows.
A static member function can access only static member data, static member functions
and data and functions outside the class. A non-static member function can access all of
the above including the static data member.
A static member function can be called, even when a class is not instantiated, a non-
static member function can be called only after instantiating the class as an object.
A static member function cannot be declared virtual, whereas a non-static member
functions can be declared as virtual
A static member function cannot have access to the 'this' pointer of the class.

The static member functions are not used very frequently in programs. But nevertheless,
they become useful whenever we need to have functions which are accessible even when
the class is not instantiated.

Page 11 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

Important Questions(C++ Programs to be done by each student)


Note: All Program should be done using “Class” concept only

Set 1
1. Write a C++ program to demonstrate nested if…else statements.
2. Write a C++ program to find roots of quadratic equation.
3. Write a C++ program to find the greatest number among two numbers.
4. Write a C++ program to find the greatest number among three numbers.
5. Write a C++ program to swap two numbers.
6. Write a C++ program (using IF..ELSE and SWITCH CASE) to find the grade.
a. If percentage is between 51 to 60 then give grade as ‘C’
b. If percentage is between 61 to 70 then give grade as ‘B’
c. If percentage is between 71 to 80 then give grade as ‘A’
d. If percentage is greater than 80 give grade as ‘A+’
7. Write a C++ program to find the PF (12%), TA (10%), HRA (15%) based on the
basic salary of an employee.[Net Salary = (PF+TA+HRA+BASIC)-PF]
a. Also Calculate bonus as 5% if Net Salary>12,000

Set 2

8. write a C++ program to print sum of all squares between 1 to n.


9. write a c++ program to sort the numbers of an array.
10. write a C++ program to check whether a given number is Armstrong or not.
11. write a c++ program using class to find the GCD of two numbers.
12. write a c++ program using the function concept to generate Fibonacci series.

Set 3

13. Write a C++ program to demonstrate parameter passing methods (call by value &
call by reference).
14. Write a C++ program to swap two numbers using function (using call by value).
15. Write a C++ program to swap two numbers using function (using call by
reference).
16. Write a C++ program to demonstrate the concept of recursion.
17. Write a C++ program to find the factorial of n using recursion.
18. Write a C++ program to find the factorial of a given number n using functions/
recursion. Use single return value function.
19. Write a C++ program to check whether a given number is Armstrong or not using
function.
20. Write a C++ program to demonstrate macros.
21. Write a C++ program to demonstrate inline function.
22. Write a C++ program to demonstrate passing array as function parameter.
Set 4

23. Write a C++ program to demonstrate class concept.


24. Write a C++ program to accept student rno, 3 subject marks and display.
25. Write a C++ program to accept student rno, 3 subject marks and also calculate
total and average, and display the result.
26. Write a C++ program to declare two variables in private and public section and try
to access these variables outside the class and note your observation.

Page 12 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

27. Write a C++ program to transpose a matrix using class concept notation.
Set 5

28. Write a C++ program to generate Fibonacci series using class.


29. Write a C++ program to sort an array of elements with the help of classes.
30. Write a C++ program to find sum of digit of a given number using class.
31. Write a C++ program to perform matrix multiplication using class.
32. Write a C++ program to find area of a triangle, square, rectangle using function
overloading.
33. Write a C++ program to demonstrate inline function and macro.
34. Write a C++ program to find the maximum element in an array
35. Write a C++ program to check whether a string is palindrome or not.
36. Write a C++ program to reverse the number.
37. Write a C++ program to demonstrate friend function.
38. Write a C++ program to demonstrate mechanism of accessing data members and
member functions for the following cases:
i) Inside a member function of the same class.
ii) Inside a member function of another class.
39. Write a C++ program to store details of 5 students and display the same.
40. Write a C++ program to demonstrate static data member and static member
function.

Set 6

41. Write a C++ program to demonstrate default constructor.


42. Write a C++ program to demonstrate constructor and destructor.
43. Write a C++ program to demonstrate parameterized constructor.
44. Write a C++ program to demonstrate copy constructor.
45. Write a C++ program using class to find the GCD of two numbers using
constructors and destructors.
46. Write a C++ program to add two complex numbers using constructor overloading.
47. Write a C++ program to demonstrate friend function accessing private data
member of a class.

Set 7

48. Write a C++ program to demonstrate single inheritance.


49. Write a C++ program to demonstrate multilevel inheritance.
50. Write a C++ program to demonstrate multiple inheritance.

Set 8

51. write a program to demonstrate hierarchical inheritance.


52. write a program to demonstrate hybrid inheritance.
53. write a program to demonstrate multipath inheritance.
54. write a program to demonstrate virtual base class.

Page 13 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

(Special notes on Constructors in theoretical concept, Exam point of view)

Constructors:
Constructors in C++ are special member functions of a class. They have the same name as the Class
Name. There can be any number of overloaded constructors inside a class, provided they have a
different set of parameters. There are some important qualities for a constructor to be noted.

Constructors have the same name as the class.


Constructors do not return any values
Constructors are invoked first when a class is initialized. Any initializations for the class
members, memory allocations are done at the constructor.

Default Constructor:
Constructor with no parameter is called default constructor.
Eg: <class name>()
{ //function body
}

Parameterized Constructor:
Constructor with parameter(s) are called parameterized constructor.
Eg: <class name>(argument(s))
{ //function body
}

Copy constructor:

It is used to make deep copy of objects.

There are 3 important places where a copy constructor is called.

1. When an object is created from another object of the same type


2. When an object is passed by value as a parameter to a function
3. When an object is returned from a function

If a copy constructor is not defined in a class, the compiler itself defines one. This will ensure a
shallow copy. If the class does not have pointer variables with dynamically allocated memory, then
one need not worry about defining a copy constructor. It can be left to the compiler's discretion.

But if the class has pointer variables and has some dynamic memory allocations, then it is a must to
have a copy constructor.

For ex:
class A //Without copy constructor
{
private:
int x;
public:
A() {A = 10;}
~A() {}
}

Page 14 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

class B //With copy constructor


{
private:
char *name;
public:
B()
{
name = new char[20];
}
~B() // destructor
{
delete name[];
}
B(const B &b) //Copy constructor
{
name = new char[20];
strcpy(name, b.name);
}
};

Let us imagine if you don't have a copy constructor for the class B. At the first place, if an object is
created from some existing object, we cannot be sure that the memory is allocated. Also, if the
memory is deleted in destructor, the delete operator might be called twice for the same memory
location.

This is a major risk. One happy thing is, if the class is not so complex this will come to the fore during
development itself. But if the class is very complicated, then these kind of errors will be difficult to
track.

Destructors:
Destructors in C++ also have the same name, except for the fact that they are preceded by a '~' (tiled)
operator. The destructors are called when the object of a class goes out of scope. It is not necessary
to declare a constructor or a destructor inside a class. If not declared, the compiler will automatically
create a default one for each. If the constructor/destructor is declared as private, then the class
cannot be instantiated.

Constructor with no arguments is called default constructor, constructor with parameters is


called parameterized constructor, constructor with argument as of class name is called copy
constructor.

Page 15 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

Example:
class example_class //Sample Class
{
private:
int x; //Data member
int y; // Data member
public:
example_class() //Default Constructor
{
x = 0;
y = 0;
}

example_class(int a,int b) //Parameterized Constructor


{
x = a;
y = b;
}

example_class(exam_class & a) //Copy Constructor


{
x =a.x;
y = a.y;
}

~example_class() //destructor
{}

int Add()
{
return x+y;
}
};

void main()
{
example_class obj1; // default constructor is invoked
example_class obj2(10,20); // parameterized constructor is invoked
example_class obj3(obj2); // copy constructor is invoked, object obj2 will be copied in object obj3
}

Friend Function:

Any data which is declared private inside a class is not accessible from outside the class. A function
which is not a member or an external class can never access such private data. But there may be
some cases, where a programmer will need access to the private data from non-member functions
and external classes. C++ offers some exceptions in such cases.
A class can allow non-member functions and other classes to access its own private data, by
making them as friends.
Once a non-member function is declared as a friend, it can access the private data of the
class
similarly when a class is declared as a friend, the friend class can have access to the private
data of the class which made this a friend

Page 16 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

(Special notes on INHERITANCE in theoretical concept, Exam point of view)

Inheritance:

Creating or deriving a new class using another class as a base is called inheritance in C++. The new
class created is called a Derived class and the old class used as a base is called a Base class in
C++ inheritance terminology.

The derived class will inherit all the features of the base class in C++ inheritance. The derived class
can also add its own features, data etc., It can also override some of the features (functions) of the
base class, if the function is declared as virtual in base class.

C++ inheritance is very similar to a parent-child relationship. When a class is inherited all the
functions and data member are inherited, although not all of them will be accessible by the member
functions of the derived class. But there are some exceptions to it too.

Inheritance is the mechanism which allows a class B to inherit properties of a class A. We say
``B inherits from A''. Objects of class B thus have access to attributes and methods of class A
without the need to redefine them.

In C++, inheritance defines an "is a" relationship. The derived class is a type of its base
class. For instance, a "cat" class could be derived from an "animal" class. A cat is an
animal. A cat is a type of animal. A derived class inherits both the data members and
methods of its base class. It may also define additional members and methods that
support specialized functionality.

Inheritance provides reusability of component


Inheritance provides extensibility of features
Private data members or member functions can never be inherited
Private members of the base class are not accessible from within the derived class i.e. private
members can never be inherited
The constructor and destructor of a base class are not inherited
The assignment operator is not inherited
The friend functions and friend classes of the base class are also not inherited
Private members of the base class are not accessible from the derived class
Protected members can be accessed by member function of its own class and from any class
derived from that class. Protected members cannot be accessed from the function outside
the class and not also from main function.
When the base class is inherited via “Protected Derivation” by the derived class, “Protected
Members” of the base class is accessible member function of its own class and any class
immediately derived from it. It cannot be accessed by any other class or functions.

 When a base class is “Privately Inherited” by a derived class, “Public Members” of the base
class becomes “Private Members” of the derived class and therefore the public members of
base class can only be accessed by the member functions of the derived class. They are
inaccessible to the objects of the derived class.
 When a base class is “Publicly Inherited” by a derived class, “Public Members” of the base
class becomes “Public Members” of the derived class and therefore they are accessible by
the objects of the derived class.

Superclass/Subclass:

Page 17 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

If class A inherits from class B, then B is called superclass of A. A is called subclass of B.


Objects of a subclass can be used where objects of the corresponding superclass are expected.
This is due to the fact that objects of the subclass share the same behaviour as objects of the
superclass.

Superclasses are also called parent classes. Subclasses may also be called child classes or
just derived classes. You can again inherit from a subclass, making this class the superclass
of the new subclass. This leads to a hierarchy of superclass/subclass relationships. If you
draw this hierarchy you get an inheritance graph.

Types of Inheritance:

(1) Single Inheritance (2) Multilevel Inheritance (3) Multiple Inheritance


(4) Hierarchical Inheritance (5) Hybrid Inheritance (6) Multipath Inheritance.

(Refer Class Notes for more details)

Example:(single inheritance)

class vehicle //Sample base class


{
protected:
char colorname[20];
int number_of_wheels;
public:
vehicle();
~vehicle();
void start();
void stop();
void run();
};

class Car : public vehicle //Sample derived class


{
protected:
char type_of_fuel;
public:
Car();
};

The derived class Car will have access to the protected members of the base class. It can also use
the functions start, stop and run provided the functionalities remain the same.

In case the derived class needs some different functionalities for the same functions start, stop and
run, then the base class should implement the concept of virtual functions.

Page 18 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

Single Inheritance: When one new class is derived from an existing class then this type of
inheritance is said to be single inheritance

class A
{
---
---
};
class B : public A
{
---
---
};

Multilevel Inheritance: When one new class say B, is derived from an existing class say A,
and again one new class say C, is derived from the class say B which is already derived from
some other class. Then this type of inheritance is said to be multilevel inheritance.
class A
{
---
---
};
class B
{
---
---
};
class C : public B
{
---
---
};

Multiple Inheritance: When a new class is derived from more than one class then this type
of inheritance is said to be multiple inheritance.
class A
{
---
---
};
class B
{
---
---
};
class C : public A, public B
{
---
---
};

Page 19 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

Example:
class a {
public:
int i;
};

class b {
public:
float j;
};

class c : public a, public b {


int k;
};

Hierarchical Inheritance: When more than one class is derived from a single base class then
this type of inheritance is said to hierarchical inheritance.

class A
{
---
---
};
class B : public A
{
---
---
};
class C : public A
{
---
---
};

class D : public A
{
---
---
};

Hybrid Inheritance: Combination of any of the above inheritances leads to the result of the
hybrid inheritance.

class A
{
---
---
};

Page 20 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science

class B
{
---
---
};
class D
{
---
---
};

class C: public A, public B, public D


{
---
---
};

Multipath Inheritance: Assume there are two child classes (B,C) inheriting from the same
parent class (A) and a grand child (D) inherits from both B and C, then this type of
inheritance is called multipath inheritance.
class A
{
---
---
};
class B: public A
{
---
---
};
class C : public A
{
---
---
};
class D: public B, public C
{
---
---
};

Page 21 of 21

You might also like