c++ Notes
c++ Notes
of Computer Science
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.
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++:
VARIABLES
FUNCTIONS
FUNCTION PROTOTYPE
SYNTAX:
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();
}
#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 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.
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.
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.
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);
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
If above is the function prototype then the following statements are valid,
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)
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.
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
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.
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.
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
Page 9 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science
DESTRUCTORS:
Class time
{
Private:
int hours;
int minutes;
Public:
void gettime(int,int);
void puttime();
void addtime(time t1,time t2);
};
void time::puttime()
{
cout<<”\n hours=”<<hours<<endl;
cout<<”\n mins=”<<mins;
}
Page 10 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science
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 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
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
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
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
Set 6
Set 7
Set 8
Page 13 of 21
Aurora’s Degree College [C++ Notes] Dept. of Computer Science
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.
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:
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
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.
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() //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
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.
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
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:
Example:(single inheritance)
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;
};
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
{
---
---
};
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