C++ Programming
C++ Programming
Introduction to C++
Presented By:
Ms. Nidhi Agrawal
Assistant Professor, SOC IPS Academy
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 2
Introduction to C++
C++ is a statically typed, compiled, general-purpose,
case-sensitive, free-form programming language that
supports procedural, object-oriented, and generic
programming.
C++ History
C developed by Dennis Ritchie at AT&T
Bell Labs in the 1970s.
Used to maintain UNIX systems
Many commercial applications written in c
OOP Characteristics
Encapsulation
Information hiding
Objects contain their own data and algorithms
Inheritance
Writing reusable code
Objects can inherit characteristics from other objects
Polymorphism
A single name can have multiple meanings depending
on its context
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 7
C++ keywords
Keywords appear in blue in Visual C++.
Each keyword has a predefined purpose in the language.
Do not use keywords as variable and constant names!!
The complete list of keywords is on page 673 of the
textbook.
We shall cover the following keywords in this class:
bool, break, case, char, const, continue,
do, default, double, else, extern, false,
float, for, if, int, long, namespace,
return, short, static, struct, switch,
typedef, true, unsigned, void, while
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 8
Explanation of code
<iostream>
It is used to define the cout, cin and cerr objects, which correspond to
standard output stream, standard input stream and standard error stream,
respectively.
Standard output stream (cout)
C++ Enumeration
Enumerated type (enumeration) is a user-defined data type which
can be assigned some limited values. These values are defined
by the programmer at the time of declaring the enumerated type.
Program
#include <iostream>
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
int main()
{
cout <<"The value of enum color : "<<red<<","<<black;
cout <<"\nThe default value of enum suit :
"<<heart<<","<<diamond<<","<<spade<<","<<club;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 13
Sample Program
#include <iostream.h>
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 14
C++ VARIABLES
Example
#include <iostream.h>
// Global variable declaration:
Int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization OUTPUT=???
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 17
OPERATORS
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 18
ARITHMETIC OPERATORS
#include<iostream.h> c=a*b;
#include<conio.h> cout<<c;
void main() c=a/b;
{ cout<<c; c=a+
Int a, b,c;cout<<“enter +;
the value for a and b”;
cout<<“incrementation of a by
cin>>a>>b; one”<<c;
c=a+b; c=a--;
cout<<c; cout<<”decrementation of a by
c=a-b; one”<<c); }
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 19
RELATIONAL OPERATORS
#include<iostream.h> if(a<=b)
#include<conio.h> cout<<”a is less than or equal to b”;
void main() if(a>=b)
{ cout<<“a is greater than or equal to b”;
int a , b; if(a==b)
a=10; b=13; cout<<”a is equal to b”;
if(a<b) if(a!=b)
cout<<“a is less than b”; cout<<”a is not equal to b”;
}
if(a>b)
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 20
LOGICAL OPERATORS
#include<iostream.h> a=0; b=10;
#include<conio.h>
if(a&&b)
void main()
cout<<“condition is true”;
{
else
int a, b; a=12;
cout<<“condition is not true”;
b=10;
if(a&&b) if(!(a&&b))
cout<<“condition is true”;
cout<<”conditio }
n is true”;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 21
BITWISE OPERATOR
Bitwise operator works on bits and perform bit-by-bit operation.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 22
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100 ----> Binary Number for 60
B = 0000 1101 ----> Binary Number for 13
Program
#include <iostream.h>
int main() {
int a = 7; // a = 111
int b = 5; // b = 101
cout << "Bitwise Operators\n";
cout << "a & b = " << (a&b) << "\n";
cout << "a | b = " << (a|b) << "\n";
cout << "a ^ b = " << (a^b) << "\n";
cout << "~a = " << (~a) << "\n";
cout << "~b = " << (~b) << "\n";
cout << "a >> b = " << (a>>b) << "\n";
cout << "a << b = " << (a<<b) << "\n";
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 24
OUTPUT
ASSIGNMENT OPERATOR
An assignment operator, in the context of the C programming language, is a
basic component denoted as "=".
Int x = 25;
x = 50;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 26
In c++ are
Scope resolution operator ::
new Memory allocating operator
delete Memory release operator
endl Line feed operator
setw Field width operator
insertion <<
Extraction >>
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 27
PROGRAM
#include<iostream.h>
int n = 12; //global variable
int main()
{
int n = 13; //local variable
cout << ::n << endl;
cout << n << endl;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 29
OUTPUT
n=12
n=13
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 30
Manipulators:
ENDL
it is used in output statement and inserts a line feed. It is
similar to new line character (“\n”)
#include <iostream.h>
int main( ) {
cout << "C++ ";
cout << " Java"<<endl;
cout << “C"<<endl;
Return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 32
setw
this manipulator allows a specified width for a field that is to be printed on
screen and by default the value printed is right justified.This function is
available in header file iomanip.h.
#include<iostream.h>
#include<iomanip.h>
int main()
{
int s=123;
cout<<"s="<<setw(10)<<s ;
}
output
s= 123
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 33
Control statements
The flow of execution of statements in a program is called as control. Control
statement is a statement which controls flow of execution of the program.
Control statements are classified into following categories.
Statements that are executed when a condition is true. These statements are
divided into three categories. they are
1.Simple if
2.if else
3.nested if else
4.If else ladder
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 38
if statement
#include<iostream.h>
int main()
{
int a,b;
cout<<“Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
if(b>a)
cout<<“B is larger than A\n A=”<<b;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 39
if –else statement
#include<iostream.h>
int main()
{
int a,b;
cout<<”Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
else
cout<<“B is larger than A\n A=”<<b;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 40
repetitions:
A block or group of statements executed repeatedly until some condition is
satisfied is called Loop.
One in which condition is tested before entering the statement block called
entry control.
The other in which condition is checked at exit called exit controlled loop.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 43
1.WHILE STATEMENT :
It is an entry controlled loop. The condition is evaluated and if
it is true then body of loop is executed. After execution of body the
condition is once again evaluated and if is true body is executed once
again. This goes on until test condition becomes false.
Syntax
While(test condition)
{
body of the loop
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 45
Program
#include<iostream.h>
int main()
{
int i = 1,sum = 0,n;
cout<<"Enter N"<<end;
cin>>n;
while(i<=n)
{
sum = sum + i;
i = i + 1;
}
cout<<”Sum of first”<<n<”natural numbers
is:”<<sum<<endl;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 46
DO WHILE STATEMENT
The while loop does not allow body to be executed if test condition is false. The
do while is an exit controlled loop and its body is executed at least once.
Syntax:
do
{
body
}while(test condition);
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 47
Program
#include<iostream.h>
int main()
{
Int i = 1,sum = 0,n;
cout<<”Enter N"<<endl;
cin>>n
do{
sum = sum + i;
i = i + 1;
} while(i<=n);
cout<<”Sum of first”<< n<<” natural numbers is:”<<sum;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 48
FOR LOOP :
It is also an entry control loop that provides a more concise structure.
For statement is divided into three expressions each is separated by
semicolon;
Program
#include<iostream.h>
int main()
{
Int i ,sum = 0,n;
cout<<”Enter N";
cin>>n;
for(i=1;i<=n;i++)
{
sum = sum + i;
}
cout<<“Sum of first”<<n<<” natural numbers is:%d”<<sum;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 50
1)Goto
2)Break
3)Continue
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 51
Goto:
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 52
Program
#include<iostream.h>
int main()
{
int i ,sum = 0,n;
cout<<”Enter N";
cin>>n;
i=1;
Lable1:
sum = sum + i;
i++;
if(i<=n)
goto Lable1;
cout<<“Sum of first “<<n<” natural numbers is”<<sum;
return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 53
break:-
Program
#include<iostream.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
cout<<i;
if(i == 5)
break;
}
cout<<i;
getch();
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 55
Continue:
Program
#include<iostream.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
}
cout<<j;
}
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 57
class
It is a collection of data and member functions that
manipulate data. The data components of class are
called data members and functions that manipulate
the data are called member functions. It can also
called as blue print or prototype that defines the
variables and functions common to all objects of
certain kind. It is also known as user defined data type
or ADT(abstract data type) A classis declared by the
keyword class
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 58
Syntax:-
class class_name
{
Access specifier :
Variable declarations;
Access specifier :
function declarations;
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 59
Access Control:
Access specifier or access modifiers are the labels that
specify type of access given to members of a class. These
are used for data hiding. These are also called as visibility
modes. There are three types of access specifiers
1.private
2.public
3.protected
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 60
Program
#include<iostream.h> void putdata()
class student {
{ cout<<”Roll no:”<<roll<<endl;
private: cout<<Name:”<<name<<endl;
int roll; }
char name[20]; };
public: int main()
void getdata() {
{ student s;
cout<<”Enter Roll number:”; s.getdata();
cin>>roll; s.putdata();
cout<<”Enter Name:”; returm 0;
cin>>name; }
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 62
INLINE FUNCTIONS:
An inline function is a function that is expanded in line when it is
invoked. Inline expansion makes a program run faster because
the overhead of a function call and return is eliminated. It is
defined by using key word “inline”.
General Form:
inline function-header
{
function body;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 65
2. Every time a function is called, it takes a lot of extra time in executing a series of
instructions for tasks such as jumping to the function, saving registers, pushing
arguments into the stack, and returning to the calling function.
4. C++ has different solution to this problem. To eliminate the cost of calls to small
functions, C++ proposes a new feature called inline function.
Situations where inline does not
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 66
work:
1. A function that is returning value , if it contains
switch ,loop or both then it is treated as normal
function.
2. if a function is not returning any value and it contains
a return statement then it is treated as normal
function
3. If function contains static variables then it is executed
as normal function
4. If the inline function is declared as recursive function
then it is executed as normal function
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 67
Program
#include<iostream.h> int main()
inline float mul(float x, float y)
{
{
return (x*y);
float a=12.345;
} float b=9.82;
inline double div(double p, cout<<mul(a,b);
double q) cout<<div(a,b);
{
return 0;
return (p/q);
}
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 68
2. Only one copy of that member is created for the entire class and is
shared by all the objects of that class, no matter how many objects
are created.
3. It is visible only within the class, but its lifetime is the entire
program.
Syntax:
Program
class X
{
public:
static int i;
};
int X::i=1;
int main()
{
X obj;
cout << obj.i;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 72
Program
#include<iostream.h>
class student
{
public:
static void printMsg()
{
cout<<"Welcome ";
}
};
int main()
{
student::printMsg();
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 74
Arrays of Objects:
Arrays of variables of type "class" is known as "Array of objects". An array of
objects is stored inside the memory in the same way as in an ordinary array.
Syntax:
class class_name
{
private:
data_type members;
public:
data_type members;
member functions;
};
Class_name object_name[size];
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 75
Program
#include<iostream.h> void main()
class MyClass {
{
MyClass obj[5];
int a;
public: for(int i=0;i<5;i++)
void set(int x) obj[i].set(i);
{ for(int i=0;i<5;i++)
a=x; cout<<obj[i].get();
}
getch();
int get()
{ }
return a;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 76
Reference variable
A reference variable is an alias, that is, another name for an
already existing variable and it is created with the & operator.
Reference to a variable provides alternate name for previously
defined variable. If any change made to reference variable then
there is a change to original variable.
A reference variable can be declared as follows:
Syntax:
Program
#include <iostream.h> i = 5;
int main () cout << "Value of i : " << i;
{ cout << r ;
int i; d = 11.7;
double d; cout << "Value of d :"<< d;
int & r = i; cout << s ;
double & s = d; return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 78
Reference variable
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 79
Constructor
A constructor is a special member function whose task is to initialize
the objects of its class. It is special because its name is the
same name as the class name. The constructor is invoked
whenever an object of its associated class is created. It is called
constructor because it constructs the values of data members of
the class. In other words A constructor in C++ is a special
method that is automatically called when an object of a class is
created.
CHARACTERISTICS OF
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 80
CONSTRUCTOR
1. They should be declared in the public section.
2. They are invoked automatically when the objects are created.
3. They do not have return type, not even void.
4. They cannot be inherited, though a derived class can call the
base class constructor.
5. Like other c++ functions, they can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.
8. They make “implicit calls‟ to the operators new and delete
when memory allocation is required.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 81
Types of constructor
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 82
1.Default Constructor:
Program
#include <iostream.h> int main(void)
class Website {
{ Website obj1;
public: Website obj2;
Website() return 0;
{ }
cout<<"Welcome "<<endl;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 84
Parameterized Constructors:-
Program
#include <iostream.h> int main(void)
class Add {
{ Add obj1(10, 20); //implicit call
public: Add obj2 = Add(50,
60);//explicit call
Add(int num1, int num2) return 0;
}
{ cout<<(num1+num2)<
<endl;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 86
Copy Constructor
A copy constructor is used to declare and initialize an object from another
object. Copy Constructor is a type of constructor which is used to create a
copy of an already existing object of a class type.
Eg:
item t2(t1);
or
item t2=t1;
Syntax of Copy Constructor
Classname(const classname & objectname)
{
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 87
Program
#include<iostream.h> void display()
class Sample {
{ cout<<x<<" "<<y<<endl;
private: int x, y; }
public: };
Sample(int x1, int y1) int main()
{ x = x1; {
y = y1; Sample obj1(10, 15);
} Sample obj2 = obj1;
Sample (const Sample&sam) { obj1.display();
x = sam.x; obj2.display();
y = sam.y; return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 88
Another program
class sample void display()
{ {
int n; cout<<n;
}
public: };
sample() void main()
{
{
n=0;
sample A(100);
}
sample B(A);
sample(int a)
sample C=A;
{
n=a; sample D;
} D=A;
sample(sample &x) A.display();
{ B.display();
n=x.n; C.display();
} D.display();}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 89
DESTRUCTORS:
A destructor, is used to destroy the objects that have been created by a
constructor. Like a constructor, the destructor is a member function whose
name is the same as the class name but is preceded by a tilde.
Eg: ~item() { }
1. A destructor never takes any argument nor does it return any value.
2. It will be invoked implicitly by the compiler upon exit from the program to
clean up storage that is no longer accessible.
Program
#include<iostream.h> ~Marks() {
class Marks cout << "Inside "<<endl;
{ cout << "C++ "<<endl;
public: }
int maths; };
int science; int main( )
Marks() {
{ Marks m1;
cout << "Inside"<<endl; Marks m2;
cout << "C++ "<<endl; return 0;
} }
C++ Overloading
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 91
When we create two or more members of a class having the same name but
different in number or type of parameters, it is known as C++ overloading. In
C++, we can overload:
methods,
constructors, and
operator
Types of overloading in C++
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 92
Function overloading
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 93
Advantages of function
Overloading in C++
We use function overloading to save the memory space, consistency, and
readability of our program.
With the use function overloading concept, we can develop more than one
function with the same name
Program
#include <iostream> int main()
int add(int a, int b) {
{
cout << a+b <<endl; add(20, 40);
return 0;
} add(40, 20, 30);
int add(int a, int b, int c) }
{
cout << a+b+c <<endl;
return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 97
By having different types of Arguments
Program
#include <iostream.h> int main()
int add(int x, int y) {
{ add(20, 40);
cout<< x+y << endl; add(23.45f, 34.5f);
return 0; add(40.24, 20.433);
}
float add(float a, float b) }
{
cout << a+b << endl;
return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 99
Disadvantages of function Overloading in C++
Function declarations that differ only by its return type cannot be overloaded
with function overloading process.
Member function declarations with the same parameters or the same name
types cannot be overloaded if any one of them is declared as a static
member function.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 100
Function Overloading and Ambiguity
When the compiler is unable to decide which function it should invoke first
among the overloaded functions, this situation is known as function
overloading ambiguity. The compiler does not run the program if it shows
ambiguity error. Causes of Function Overloading ambiguity:
Type Conversion.
Function with default arguments.
Function with a pass by reference
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 101
Type Conversion:
#include<iostream.h> int main()
void function(float); {
void function(int);
function(3.4);
void function(float x)
{
function(34);
std::cout << "Value of x is : " return 0;
<<x<< std::endl; }
}
void function(int y)
{
std::cout << "Value of y is : "
<<y<< std::endl;
Function with Default
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 102
Arguments:
#include<iostream.h>
void function(int);
int main()
void function(int,int); {
void function(int x) function(12);
{
std::cout << "Value of x is : " <<x<< return 0;
std::endl; }
}
void function(int y, int z=12)
{
std::cout << "Value of y is : " <<y<<
std::endl;
std::cout << "Value of z is : " <<z<<
std::endl;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 103
In C++, We can have more than one constructor in the class with the same
name, as long as each has a different list of arguments. This concept is
known as Constructor Overloading and is quite similar to
function overloading.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 105
Program
#include <iostream.h> ABC(int a , int b)
{
class ABC
x = a; y = b;
{ }
private: void display()
int x,y; {
cout << "x = " << x << " and " << "y = " << y <<
public: endl; }
ABC () };
{ int main()
x = y = 0; {
ABC cc1;
} ABC cc2(10);
ABC(int a) ABC cc3(10,20);
{ cc1.display();
x = y = a; cc2.display();
cc3.display();
} return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 106
OPERATOR OVERLOADING
C++ has the ability to provide the operators with as special meaning for a
data type. The mechanism of giving such special meanings to an operator is
known as operator overloading. Operator overloading is a compile-time
polymorphism in which the operator is overloaded to provide the special
meaning to the user-defined data type. Operator overloading provides a
simple and easy way for the development of new definitions for most of the
operators in C++.
Operator that cannot be overloaded are as follows:
program
#include <iostream.h> Height operator+(Height& d2)
{
class Height
Height h3;
{
h3.feet = feet + d2.feet;
public: h3.inch = inch + d2.inch;
int feet, inch; return h3;
Height() }
{ };
feet = 0; int main()
inch = 0; {
} Height h1(3, 7);
Height h2(6, 1);
Height(int f, int i)
Height h3;
{
h3 = h1 + h2;
feet = f; cout << "Sum of Feet & Inches: " <<
inch = i; h3.feet << "'" << h3.inch << endl;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 112
Program
#include <iostream.h> void operator-()
class Height { {
public: feet--;
int feet, inch; inch--;
Height(int f, int i) cout << "Feet & Inches after decrement: " << feet
{ << " ' " << inch <<endl;
feet = f; }
inch = i; };
} int main()
{
Height h1(6, 2);
-h1;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 114
FRIEND FUNCTIONS:
The private members cannot be accessed from outside the class. i.e.… a non
member function cannot have an access to the private data of a class. In C++ a
non member function can access private by making the function friendly to a
class.
Definition:
Program
class sample int sum(sample s)
{ {
int x,y; int sum;
public: sum=s.x+s.y;
sample(int a,int b); return 0;
friend int sum(sample s); }
}; void main()
sample::sample(int a,int b) {
{ Sample obj(2,3);
x=a;y=b; int res=sum(obj);
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 116
Inheritance in C++
The mechanism of deriving a class from another class is known
as Inheritance.
Syntax:
class DerivedClass : AccessSpecifier BaseClass
Types of Inheritance.
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 119
Single Inheritance
In Single Inheritance, one class is derived from another class.
It represents a form of inheritance where there is only one base and
derived class.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 120
Multiple Inheritance:
multiple inheritance
#include <iostream.h> class Car: public Vehicle, public
FourWheeler
Class Vehicle{
{
public:
Vehicle()
};
{
int main()
cout << "This is a Vehicle" << endl;
{
}
Car obj;
};
return 0;
class FourWheeler {
}
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle“;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 123
3.Multilevel Inheritance
In this type of inheritance, a derived class is created from another
derived class.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 124
Program
class Vehicle class Car: public fourWheeler
{ {
public: public:
Vehicle()
car()
{
{
cout << "This is a Vehicle" << endl;
} cout<<"Car has 4
}; Wheels"<<endl;
class fourWheeler: public Vehicle }
{ public: };
fourWheeler()
{ int main()
cout<<"Objects with 4 wheels are {
vehicles"<<endl;
} Car obj;
}; return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 125
Hierarchical Inheritance
In this type of inheritance, more than one sub class is inherited from a
single base class. i.e. more than one derived class is created from a
single base class.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 126
Program
#include <iostream> int main()
class Vehicle {
{ Car obj1; Bus obj2;
public:
return 0;
Vehicle()
{ }
cout << "This is a Vehicle" << endl;
}
};
class Car: public Vehicle
{
};
class Bus: public Vehicle
{
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 127
Program
#include <iostream.h> class Car: public Vehicle
class Vehicle
{
{
};
public:
Vehicle()
class Bus: public Vehicle, public Fare
{ {
cout << "This is a Vehicle"
<< endl; };
}
};
class Fare int main()
{ {
public: Bus obj2;
Fare() return 0;
{cout<<"Fare of Vehicle\n";
}
}
};
Function Overriding
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 129
If derived class defines same function as defined in its base class, it is known
as function overriding in C++. It is used to achieve runtime polymorphism.
It enables you to provide specific implementation of the function which is
already provided by its base class.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 130
Program
#include <iostream.h> int main()
class Animal { {
public: Dog d = Dog();
void eat(){
d.eat();
cout<<"Eating...";
} return 0;
}; }
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 131
Virtual function
They are always defined in base class and overridden in derived class. It is
not mandatory for derived class to override (or re-define the virtual
function), in that case base class version of function is used.
A class may have virtual destructor but it cannot have a virtual constructor.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 133
More points
Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
Program
#include <iostream> class derived : public base {
public:
class base { void print()
public: {
cout << "print derived class" << endl;
virtual void print() }
{
void show()
cout << "print base class" <<
{
endl; cout << "show derived class" << endl;
} }
};
In C++ programming, this is a keyword that refers to the current instance of the
class. There can be 3 main usage of this keyword in C++.
Program
#include <iostream.h> int main()
class Employee { {
public: Employee e1 =Employee(101, "Sonoo", 890000);
int id; Employee e2=Employee(102, "Nakul", 59000);
string name; e1.display();
float salary; e2.display();
Employee(int id, string name, float salary) return 0;
{ }
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 137
Program
#include<iostream>
class Person { class Student : public Person {
public: public:
Person(int x) Student(int x):Person(x) {
{ cout<<"Student::Student(int ) called"<<
cout << "Person::Person(int ) called" << endl; endl;
} }
}; };
Apart from these functions, C++ introduces two new operators which are
more efficient to manage the dynamic memory. These are ‘new’ operator for
allocating memory and ‘delete’ operator for de-allocating memory.
The “new” Operator
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 141
The “new” operator allocates memory for a variable or any other entity on a
heap.
The data type mentioned above can be any valid data type supported by C++.
It can be a built-in datatype or any user-defined data type including classes
and structures.
The Delete Operator
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 142
The memory allocated dynamically using the new operator has to be freed
explicitly by the programmer. For this purpose, we are provided with the
“delete” operator.
The general syntax of the delete operator is:
delete pointer_variable;
So we can free the memory allocated to the ptr variable above as follows:
delete ptr;
This statement frees the memory allocated to the variable “ptr” back to the
memory pool.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 143
Program
#include<iostream.h> for(i=0;i<5;i++)
#include<conio.h> {
void main() cout<<"\nEnter any number : ";
{ cin>>ptr[i];
int size,i; }
int *ptr; for(i=0;i<5;i++)
cout<<"\n\tEnter size of Array : "; cout<<ptr[i]<<", ";
cin>>size; delete[] ptr;
ptr = new int[size]; }
THANK YOU