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

Unit-2 and Unit-3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit-2 and Unit-3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

An OVERVIEW OF C++

Unit 2 & Unit 3


BTECH – CSE (3rd Semester )
Presented By
DEEPTI GOUR
Iintroduction 2

What is OOP‟s?
Features
POP & OOP Comparison
Class & Object
Inheritance & Its Types
Constructor & Destructors
Functions – Inline ,Friend & Virtual
Virtual Class
Introduction
3

✖ C++ is an enhanced version of the C language.


✖ C++ adds support for OOP without sacrificing any of C’s
power, elegance, or flexibility.
✖ C++ was invented in 1979 by Bjarne Stroustrup at Bell
Laboratories in Murray Hill, New Jersey, USA.
✖ The elements of a computer language do not exist in a
void, separate from one another.
✖ The features of C++ are highly integrated.
✖ Both object-oriented and non-object-oriented programs
can be developed using C++.
What is OOP’s?
4

OOP is a powerful way to approach the task of programming.


OOP encourages developers to decompose a problem into its
constituent parts.
Each component becomes a self-contained object that contains
its own instructions and data that relate to that object.
So, complexity is reduced and the programmer can manage
larger programs
5
Continue..

All OOP languages, including C++, share three common


defining traits:

• Encapsulation (Binds together code and data)


• Polymorphism (Allows one interface, multiple methods)
• Inheritance (Provides hierarchical classification &
Permits reuse of common code and data)
6
Advantages of OOP‟s
✖ The objects are processed by their member data and functions. It is easy to
analyze the user requirements.
✖ With the help of inheritance, we can reuse the existing class to derive a new
class such that the redundant code is eliminated, and the use of existing
class is extended. This saves time and cost of program.
✖ Modular approach is used for write code. (Real-Time & Large Problem in
reduce Code))
✖ In OOP, data can be made private to a class such that only member functions
of the class can access the data. This principle of data hiding helps the
programmer to build a secure program that cannot be invaded by code in
other part of the program.
✖ It is very easy to partition the work in a project based on objects.
✖ It is possible to map the objects in problem domain to those in the program.
✖ With the help of polymorphism, the same function or same operator can be
used for different purposes. This helps to manage software complexity
easily.
7
Basic concepts of cpp

1. Object
2. Classes
3. Data Abstraction & Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing
CLASS & OBJECT 8

✖ A class represents a set of related objects. (class is a blue print of


an object.)
✖ It is a user defined data type, which consists of both data and
functions into a single unit.
✖ Once a class has been defined we can create any number of
objects.
✖ Each object is associated with the data of type class which they
were created.
✖ class provides the concept of Encapsulation. (Data Encapsulation:
The wrapping up to data and functions into a single unit (class) is
known as encapsulation.)
✖ class provides the concept of Data hiding with private
declarations.
CLASS SYNTAX & EXAMPLE 9

Syntax

[access specifier]
Class<Keyword> < class name >
{ Access specifier : variable declarations;
Access specifier :
method declarations & implementations };
NOTE:
In C++ Private data should be accessed only by member functions of the same class.
Member functions : The functions which are declared inside the class are called as
member functions.
Default access specifier in C++ is private.
private members are not directly accessible from out side the class.
10
11
Object 12

A class is only logical representation of data.


Henceforth to work with the data represented by the class you must create a variable
for the class - which is called as an object.
Object is the basic unit of object-oriented programming.

NOTE:
In a class to access data members first memory have to be allocated.
No memory is allocated when a class is created. Memory is allocated only when an
object is created, i.e., when an instance of a class is created. Object is physical copy
and class is logical copy.
Syntax :
for creating an object :
class name followed by variable name;
Demo1 obj1;
13

✖ Data Abstraction: ✖ Data Encapsulation:


Abstraction refers to The wrapping up to
the act of data and functions
representing into a single unit
essential-features (class) is known as
without including encapsulation.
the background
details or
explanations.
Inheritance
14

✖ The concept of inheritance provides the idea of reusability. Instead of


rewriting the code you can create the class from the existing class and
extending the functionality of existing class. This mean that we can add
additional features to an existing class with out modifying it.
✖ Example:
\ The animal class is divided into mammals, amphibians, insects, birds,
and so on.
\ The vehicle class is divided into cars, trucks, buses, motorcycles, and so
on.
✖ Creating a new class from an existing class or base class is called
Inheritance. The base class is also known as parent class or super class,
The new class that is formed is called derived class. Derived class is also
known as a child class or sub class. Inheritance helps in reducing the
overall code size of the program, which is an important concept in
object-oriented programming.
15

Polymorphism
Polymorphism comes from the Greek words “poly” and “morphism”.
“poly” means many and “morphism” means form
i.e.. many forms. Polymorphism means the ability to take more than one form.
Advantage of this is you can make an object behave differently in different
situations, so that no need to create
Polymorphism can be achieved with the help of Overloading and Overriding
concepts and it is classified into compile time polymorphism and Runtime
polymorphism.
Function with same name but different arguments .
Functioning is different.
Example : add2i (int a, int b) add3i (int a, int b, int c)
add2f (float a, float b) add3f (float a, float b, float c)
16

Message Passing
The technique of message communication between objects
makes the interface with external systems easier.
17

1. C follows procedural
programming concepts.
2. Data is less Secured in
C.
C follows the top down
approach – prorgam
devides
SCOPE RESOLUTION OPERATOR (::) 18

Unary Scope Resolution Operator


Used to access a hidden global variable

Binary Scope Resolution Operator


Used to associate a member variable & member function with
its class and also used to access a hidden class member
variable.
C++ Header Files 19

What Are C++ Header Files?


Header files that store predefined functions. It contains definitions of
functions that you can include or import using a preprocessor directive
#include.

This preprocessor directive tells the compiler that the header file needs to
be processed prior to the compilation. For example, the <iostream>
header file in C++ contains the definition of input-output functions.
✖ Standard library header files
✖ User-defined header files
✖ The name of the header file is enclosed in double quotes, and this
syntax is usually preferred when you are defining a user-defined
header file.
20

Continue ….

✖ Standard library header ✖ User-defined header files:


files: These are those These are those header files
header files that are defined by the user and can be
already present in the used by including them in the
compiler of C++; you just program using #include.
need to import them to use
them.
21
22
23
C++ Keywords 24

A keyword is a reserved word. (Use as a variable name, constant name


etc. )
A list of 32 Keywords in C++ Language given below.
C++ Operators 25
INHERITANCE 26

The process by which one class object (Data Syntax:


member & Function ) derive the properties
Class Class1
of other classes or classes while
maintaining its own is called Inheritance. {
// /Body ;
The parent class from which other classes };
are derived is called a base /super /root
Class Class2 : Public Class1
class, whereas the child classes that are
generated out of the base classes are called {}
the derived /child/ subclasses.
Create an object easy to
For enable reusability, extendability, and access (as multiple objects)
modifiability easier in code. ( use all class and maintain.
properties in easy mode & practical - with
save time & efforts)
27

INHERITANCE TYPES
1. Single Inheritance
2. Multiple Inheritance
3. Multi-level Inheritance
4. Hierarchal Inheritance
5. Hybrid Inheritance
28
Single Inheritance
✖ Single or simple Inheritance - In this Class A1
type of inheritance, a sub class derives
properties from a single super class.
Class B1

✖ Multiple Inheritance - In this type of


Class A1 Class B1
inheritance, a sub class derives
properties from multiple super classes.

Class Z1
Class A 29

✖ Multilevel Inheritance - In this


type of inheritance, a subclass Class B
derives properties from another
subclass which in turn derives
Class C
properties from another sub
class or the super class.
Class D

✖ Hierarchical Inheritance - In
this type of inheritance,
multiple sub classes derive
properties from a single super
class.
30
Hybrid Inheritance

Class A

In this type of Hybrid inheritance


in C++, a combination of many
Inheritances. For example - Class B Class C
mixing Multilevel Inheritance
with Multiple Inheritance, etc.
Class D
1. #include <iostream> 31

2.using namespace std; 13.cout<<"here sunglasses order


by user - derived class demo";
3.class Order{ 14. }
4. public: 15.};
5. void display() { 16. class bag : public sunglass{
6. cout<<"here the first class for 17. };
order option ."; 18.int main() {
19. bag obj1;
7. } 20. obj1.display();
8.}; 21. sunglass obj2;
9.class sunglass: public Order 22. obj2.showorder();
10.{ 23. return 0;
24.}
11. public : void showorder () {
12.
1. #include <iostream> 32

2. using namespace std; cout<<"here derived class from


demo1";}
3. class demo1 { public:
};
4. void display() { class demo3 : public demo2 {
5. cout<<"here the first inheritance };
demo class of the program ."; int main() {
6. } demo3 obj1;
7. }; obj1.display();
8. class demo2 : public demo1 demo2 obj2;
9. { obj2.show();
10. public : void show () {
return 0;
}
11. cout<<"here derived class from
demo1";}
12. };
33

Inheritance – Access Modifier

Base Class Derived Class Accesses Modifier Visibility

Public Private Protected


Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected


34

Constructor

✖ Constructor and Destructor are the special member functions of


the class which are created by the C++ compiler or can be
defined by the user.

✖ The constructor is used to initialize the object of the class.

✖ Whereas the destructor is called by the compiler when the object


is destroyed.
35
Continue …..

✖ If you want to automatically initialize data members i.e., with


out calling member function we want to initialize data
members. It is possible only through Constructors .

✖ A constructor is a special member function.

✖ Constructors are used to initialize the objects of its class and


this is called automatic initialization of object.

✖ Constructors constructs the values of data members of class


i.e., when constructor is used data members are automatically
initialized, when the object of the class is created.
Characteristics of constructors :
36

1. Constructor name and class name should be same.


2. Constructors should be declared in public section.
3. Constructors never have any return value (or) data type
including void.
4. The main function of Constructor is to initialize objects and
allocate appropriate memory to objects.
5. Constructors can have default values and can be overloaded.
6. Constructor may or may not have arguments /parameters.
7. Constructor is executed only once when the object is created.
8. Constructor is invoked automatically when object of class is
created.
37

Syntax: Example:
Class ClassName Class Number
{ { Public: Number ()
Public: Constructor {
Name () Cout<<“Demo for
{} Contructor”;
}; }
};
38
.
outside class definition using
Constructors can be defined class name and scope resolution
either inside the class :: operator
definition
Syntax class Demo2
{ public: int i;
class Demo1 Demo2(); // constructor declared
{ public: int x; }; Demo2::Demo2() //
constructor definition { i = 100; }
Demo1() // constructor
{ // object initialization } };
define a constructor & initialize in class data member variables with constants. 39

1. #include<iostream> 13. DemoConst::DemoConst(void)


2. using namespace std; //def. constructor
3. class DemoConst { 14.{
4. private: 15.cout<<"\ n here calling to
5. int n1, n2, n3; constructor";
6. public: 16.i=4; n1=10; n2=20; n3=30;
7. int i ; 17.}
8. DemoConst(void); //declaration of 18.int main()
constructor 19.{
9. void display() 20.DemoConst i;
10. { 21.}
11. cout<<"\ n number1 is = " <<n1<<" Number
22.i.display();
2 is= "<<n2<< " Number3 = "<< n3; } 23.return 0;
Types of Constructor
40

1. Default Constructor : Constructor


C++ supports three types with out arguments are called
of Constructors Default Constructor.
1. Default Constructor. There are two types Default
2. Parameterized Constructors
Constructor.
3. Copy Constructor. 1st -System written which is created by
the compiler at compile time(When the
class is not having a Constructor.

2nd -we have to define that is called


user defined Constructor.
class Length int main() 41

{
{
//default constructor called
public: when object is created
int l; Length obj1;
//default constructor cout<<"Line size is"<<"
Length() "<<obj1.l<<" "<<"cm";
{
return 0;
l=100; }
}
};
DEFAULT CONSTRUCTOR EXAMPLE 42

1. #include<iostream> 11. void display() {


2. using namespace std; 12. cout<<"variable v1= "<<v1<<endl;
3. class defconst { 13. cout<<"variablev2= "<<v2<<endl;
14. }
4. private:
15. };
5. int v1,v2;
16. main() {
6. public:
17. defconst obj1;
7. defconst() {
18. obj1.display();
8. //define default constructor
19. return 0;
9. cout<<"default constructor
20. }
with in class & default call V1
& V2"<<endl;
10. v1=1000;v2=2000;
Parameterized Constructor 43

A constructor initialize the member variables with given values,


It is also possible to create a constructor with arguments and
such constructors are called Parameterized Constructors.
(Constructor with arguments)
44
#include<iostream> void display() {
using namespace std; cout<<“ vaiable1= "<<v1<<endl;
class paraconst { cout<<“vaiable2= "<<v2<<endl;
private: cout<<"vaiable3= "<<v3<<endl;
int v1,v2,v3; }
public: };
paraconst(int n1, int n2, int n3) { main() {
v1=n1; paraconst pc1(90,80,70);
v2=n2; pc1.display();
v3=n3; return 0;
cout<<"demo for parametrized }
constructor"<<endl;
}
45
3. Copy constructor:

The process of copying one object data in to another object is called as


Copy Constructor.

A copy constructor is a constructor which is used to initialize the


current values with another object value.

o Copy constructor is used to create another copy or xerox of one


object.
o Copy constructors are having reference type parameters.
o Copy constructors are having class type parameters means object.
o Copy constructors receives another object to initialize current
object.
46
class copyconst { void display( ) {
private: cout<<" variabl1"<<v1<<endl;
int v1,v2,v3; cout<<" variabl2"<<v2<<endl;
public: cout<<" variabl3"<<v3<<endl;
copyconst(int n1, int n2, int n3) { }
v1=n1; };
v2=n2; int main( ) {
v3=n3; copyconst C1(100,200,300);
cout<<"demo for parametrized constructor"<<endl; copyconst C2(C1);
} cout<<"here Parameterized
copyconst(copyconst &obj) // copy constructor constructor"<<endl;

{ C1.display();

v1=obj.v1; cout<<"here call copy constructor"<<en


v2=obj.v2; C2.display();

v3=obj.v3; return 0;

} }
47
48
Destructors
class ConstDest
o To release (or) delete this memory we use
destructor. (When ever constructor is executed { ConstDest() // Constructor
object is defined and memory is allocated.) { Cout<<“here constructor create
Destructors are typically used to de-allocate memory”;
memory – delete the memory created by the }
constructor.
~ConstDest() //Destructor
{
o The destructor is called whenever an
object's lifetime ends, which includes Cout<<“here destructor releases
program termination. (objects with memory”;
static storage duration) }
};
49
Reminder to create Destructor
1. Destructor name should be similar to class name and preceded by 'tilde'

operator(~).
2.Destructor should be declared in public section.
3. Destructor doesn't have any arguments or don‟t return any value (or void),
so overloading is not possible.
4. Destructor never returns a value, it makes a implicit call new and delete
operator.
5. Destructor never called with object followed by dot(.) operator.
6. Destructor never participate or use in inheritance.

Note: if an object (class object-at run time) is destroyed as it goes out of


scope.
50

Comparison in Constructor & Destructor


Constructors Destructors

1. The constructor initializes the class 1. If the object is no longer required, then
and allots the memory to an object. destructors demolish the objects.

2. If the object is no longer required, 2. When the program gets terminated, the
then destructors demolish the objects. destructor is called automatically.

3. It receives arguments & can be 3. It does not receive any argument & cant
overloaded. overloaded.

4. They are often called in successive 4. They are often called in reverse order of
order. constructor. (explicit define)

When destructor Called?


• A local /automatic object with block scope goes out of scope.
• An object allocated using the new operator is explicitly deallocated using delete.
• The lifetime of a temporary object ends.
• A program ends and global or static objects exist (Program no more use but through OOP
other features objects are exists)
Using namespace std; 51

class Demo1
{
public:
Demo1()
{cout << "when object created - constructor call" << endl; }
~ Demo1()
{ cout << "when object destroy - destructor call"<< endl; }
};
int main()
{
Demo1 *obj1= new Demo1();
delete obj;
return 0;
}
Function in C++ 52

Why need function ?


• Debugging of the code would be easier (by use function - errors are easy to be
traced.
• Use of functions reduce size of code.
• Duplicate set of statements are replaced by function calls.
• Improve reusability of code, same function can be used in any class or program.
• It improves readability of code.
• Types of Function (in c , C++, Java )
1. Library Functions 2. User Defined Functions
Function Parts/Activity :
1. Function declaration (Prototype )
Returndatatype function name (data type arguments);
2.Function definition (Body of the Function )
3.Function call
Call By Value & Call By Reference
INLINE Function
53

An inline function is a function that is expanded in line when it is invoked


thus saving time.
Inline function is used to execute the function but it not makes again the
space inside of the memory.
It copies the function to the location of the function call in compile-time
and may make the program execution faster. (Use for small Code/Project)

Problems with Inline Function :


• To Use too many inline functions then the size of the binary executable
file will be large, because of the duplication of same code.
• Too much inlining can also reduce your instruction cache hit rate.
• Inline functions may not be useful for many embedded systems.
Because in embedded systems code size is more important than speed.
54

#include <iostream>
using namespace std;
inline int
ShowNum(int n)
{
cout<<"Number is "<< n<<endl;
}
int main() {
ShowNum(10);
ShowNum(15);
return 0;
}
VIRTUAL CLASS
55

✖ Virtual Class is defined by writing a keyword “virtual” in the derived


classes, allowing only one copy of data to be copied to derived class.
✖ It prevents multiple instances of a class appearing as a parent class
in the inheritance hierarchy when multiple inheritances are used.
Example : Class A1 is the parent class, and
Classes B1 and C1 are the derived classes
from Class A1. Thus Class B1 and Class C1 have all
the properties of Class A1.

Succeeding, Class D1 inherits Class B1 and Class


C1. With our knowledge, Class D1 will get all the Class A1
properties from Class B1 and C1, which also
has Class A1 properties.
Class B1 Class C1
There will be an error because Class D1 will get
Class A1‟s properties thrice, and the compiler
can‟t decide what to output. Here compiler -
“ambiguous” when such a situation occurs. Class D1
56

Why Need Virtual Base Class

✖ To prevent the error and let the compiler work efficiently,


we’ve to use a virtual base class when multiple inheritances
occur. (saves space and avoids ambiguity)
✖ When a class is specified as a virtual base class, it prevents
duplication of its data members. Only one copy of its data
members is shared by all the base classes that use the virtual
base class.
✖ If a virtual base class is not used, all the derived classes will get
duplicated data members. In this case, the compiler cannot
decide which one to execute.
57
#include<iostream> class D1:public C1,public B1{
using namespace std; public:
class A1{ int x1;
public: };
int x; main(){
}; D1 obj;
class B1:virtual public A1{ obj.x=100;
public: obj.y=20;
int y; obj.z=30;
}; obj.x1=200;
class C1: virtual public A1{ cout<< " X : "<< obj.x;
public: cout<< " Y : "<< obj.y;
int z; cout<< "Z : "<< obj.z;
}; cout<< "X1 : "<< obj.x1;
58
59
FRIEND FUNCTIONS

All 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 members by
making the function friendly to a class.
A friend function is not a member of any class, but it is able to
access the private members of those where it is presented as a
friend.
when a data is declared as private inside a class, then it is not
accessible from outside the class. A friend function is used for
accessing the non-public members of a class.
Continue…
60

Def.: A friend function is a function which is declared within a class


and is defined outside the class. It can access private members of a
class.
Friend function declaration should be inside the class using the
Friend key word. (It does not require any scope resolution operator
for defining .)
Syntax:
friend return-type function-name(arguments);
Definition of friend function is specified outside the class .
61
Friend function characteristics
✖ It is not in scope of class.
✖ It cannot be called using object of that class.
✖ It can be invoked like a normal function.
✖ It should use a dot operator for accessing members that is inside
the friend function to access the object data member we have to
use obj name(dot operator).
✖ It can be public or private. It has objects as arguments. (majorly
used in operator overloading).
62
To Access non-member function, by using Friend function.
using namespace std; void display(userinfo ui) //Friend Fun –
access2private data
class userinfo
{
{ char name[20];
cout<<“ Details of User &
int userID;
salary”<<ui.userID<<ui.salary;
float salary;
}
public : void read()
int main()
{ cout<<“Enter Name :”; cin>>name;
{ userinfo obj ;
cout<<“Enter User ID”; cin>>userID;
cout<<“Enter Salary :”; cin>>salary; obj.read();
} display(obj);
friend void display(userinfo); return 0; //Calling of FriendFun + obj-
//Friend Fun-decl argument
}; }
63
FRIEND CLASS
It is possible to declare one or more functions as friend functions or
an entire class can also be declared as friend class.
A class can also be declared to be the friend of some other class.
When we create a friend class then all the member functions of the
friend class also become the friend of the other class. This requires
the condition that the friend becoming class must be first declared
or defined (forward declaration).

Container class : The primary class is called container class.


Contained class : The class which is declared as friend is called
contained class.
RESTRICTIONS ON FRIEND CLASSES
64

✖ Friend functions and classes are not inherited.


✖ Friend function cannot have storage-class specifier i.e. cannot be declared
as static or extern.
✖ Friend classes are not corresponded i.e. if class A is a friend of B it does
not imply that class B is a friend of A.
✖ Friend classes are not transitive: i.e. friend of a friend is not considered to
be a friend unless explicitly specified.
✖ for ex :If class A declares class B as a friend, and class B declares class C as
a friend, class C doesn’t necessarily have any special access rights to class
A.
✖ In the above program sample1 is container class.
✖ sample2 has object of sample1 , so sample2 is contained class. Declaring
the object of one class in another class is called composition relation.
✖ Composition allows the concept of reusability, i.e., one class data is
reused in another class.
class sample1 { cout<<"Enter C & D values in class sample2 : "; 65
int a,b; cin>>c>>d; }
void sum2() {
public:
sum=obj1.a+obj1.b+c+d;
friend class sample2; //declaring friend class }
void getdata1() { void display2() {
cout<<"A="<<obj1.a<<endl;
cout<<"Enter A & B values in class sample1: "; cout<<"B="<<obj1.b<<endl;
cin>>a>>b; cout<<"C="<<c<<endl;
} cout<<"D="<<d<<endl;
cout<<"SUM="<<sum<<endl;
void display1() { }
cout<<"A="<<a<<endl; };
cout<<"B="<<b<<endl; int main() {
//sample1 s1;
} }; //s1.getdata1();
class sample2 { //s1.display1();
sample2 s2;
//public: int c,d,sum;
s2.getdata2();
sample1 obj1; s2.sum2();
public: void getdata2() { s2.display2();
}
obj1.getdata1();
obj1.display1();
Pointer & Using THIS Pointer 66

✖ Pointer is a variable it holds address of another variable.


✖ Each variable occupies certain memory location at the time of
executing program and it is possible to access the address of
memory location by using pointers.
✖ A pointer variable stores the memory address of any type of
variable.
✖ The pointer variable and normal variable must be of same data
type.

✖ Pointer is denoted by ' * ' asterisk symbol.


✖ The process of allocating memory at run time is called as dynamic
memory allocation.
✖ Pointers are used in array concept and functions concept.
67
✖ pointers save memory space. Execution time with pointers is faster,
because data are manipulated with the address, that is direct access
to memory.
✖ int *v1;
✖ float *v2;
✖ char *v3;
POINTER TO CLASS
✖ Pointer is a variable it holds address of another variable and it may
be of any data type i.e., int , float , double etc., Similarly we can also
define a pointer to a class.
Example:-
class UserInfo
{ int id , int age;
}; class UserInfo *ptr;
class Userinfo{
Pointer to Class 68

public:
char name[20];
int id;
int age; };
int main() {
class Userinfo u1={"Ravi",111,35};
Userinfo *ptr;
ptr=&u1;
cout<<"User Name= "<<ptr->name<<endl;
cout<<"User id= "<<ptr->id<<endl;
cout<<" User Age= "<<ptr->age<<endl;
return 0; }
POINTER TO OBJECT 69

A pointer can point to a specified object.


When accessing members of a class given a pointer to an object, use
the arrow(->) operator instead of the dot operator.
class Userinfo{ void displayuser() {
public: cout<<"UserName= "<<name<<endl;
char name[20]; cout<<"Userid= "<<id<<endl;
int id; cout<<"UserAge= "<<age<<endl;
int age; } };
public: int main() {
void readuser() class Userinfo u1;
{ Userinfo *ptr;
cout<<"Enter User Name: "; ptr=&u1;
cin>>name; ptr->readuser();
cout<<"Enter User ID: "; ptr->displayuser();
cin>>id; return 0;
cout<<"Enter User Age: "; }
cin>>age;
}
THIS Pointer 70

„this‟ pointer represent an object that invoke or call a member


function.
It will point to the object for which member function is called.
It is automatically passed to a member function when it is called.
It is also called as implicit argument to all member function.
For example:
u1.readuser(); Here u1 is an object and u1.showuser() is a member
function. So, „this‟ pointer will point or set to the address of object
u1.
To know the current object address we use this pointer.
It is used to distinguish the data members from local variables when
both are declared with name.
Every non-static member of C++ have this local variable ' this'.
this pointer 71

class demo {
int main() {
int v1,v2;
demo dobj;
public:
dobj.read(100,200);
void read(int v1, int v2) {
dobj.show();
this->v1=v1;
return 0;
this->v2=v2;
}
}
void show() {
cout<<"V1= "<<v1<<endl;
cout<<"V2= "<<v2<<endl;
}
};
72
//this pointer
#include<iostream>
int main() {
using namespace std;
TPdemo tp;
class TPdemo {
tp.disp(200);
int v1;
return 0;
public: TPdemo() {
}
v1=10000;
}
void disp(int v1) {
cout<<"The value of argument variable 1="<<v1;
cout<<“The value of data member v1="<<this->v1;
}
};
73

Polymorphism (Function Overloading)


Polymorphism means one name multiple forms.
Polymorphism is classified into 2 branches
1. Compile Time Polymorphism/Early Binding/Static Binding: Deciding a
function call at compile time is called as compile time (or) static (or) early
binding.
2. Runtime Polymorphism/Late Binding/Dynamic Binding : Deciding a function
call at run time is called as run time (or) dynamic (or) late binding.
74
Overloading Using Different Types of Parameter
using namespace std;
int main(void) {
class displaydata{
displaydata obj1;
public:
obj1.show(100);
void show (int v1) {
obj1.show(991.75);
cout << "integer var.value: " << v1 << endl; }
obj1.show("Function
void show(double v2) { Overloading");
cout << "floating var.value: " << v2 << endl;} return 0;
void show (char* v3) { }
cout << "character var.value: " << v3 << endl;
}
NOTE : functions must have the same name and different types of parameters.
};
functions must have a different set of parameters and a different sequence of
parameters.

Overloading of functions with different return type is not allowed


75

Type Conversion
Function Overriding
76
ABSTRACT CLASS
• In C++, an abstract class is a class that cannot be instantiated on its
own but is meant to be used as a base class for other classes.

• When a class is not using for creating an object such class is known
as abstract class.

• The abstract class can act as a base class only.

• An abstract class gives a structure, using this other classes are form
as.

• A class which contains pure virtual function is called abstract base


class.
Why Abstract Class in C++
77

• By defining an abstract class, you can provide a common interface and shared functionality
that subclasses must implement or extend. This promotes code reusability and reduces
redundancy in your codebase.

• Abstract classes can have pure virtual functions, which are functions without a defined
implementation in the abstract class itself.

• Polymorphism allows you to treat objects of different classes that inherit from the same
abstract class in a uniform way. This makes it easier to work with a variety of related objects
without needing to know their specific types.

• Design for Extensibility: You can create an abstract class with a defined set of methods and
attributes and later extend it by creating new subclasses. These subclasses can add more
functionality while still adhering to the contract defined by the abstract class.

• Preventing Object Instantiation: Abstract classes cannot be instantiated on their own, which
means you cannot create objects of an abstract class. This helps ensure that the class is used
as a base for other classes and not as a standalone object.
78
#include<iostream> void disp()
using namespace std; {
class super1 { cout<<“access base class -super1- disp
public: () in derived class sub1";
virtual void disp()=0; }
int v1; };
}; int main() {
class sub2 : public super1 { super1 *s1obj;
public: sub2 obj2;
s1obj = &obj2;
s1obj->disp();
return 0;
}
79

FUNCTION OVERRIDING
Function overriding is a fundamental concept in object-oriented
programming that empowers developers to create more flexible
and specialized classes. It enables a derived class to provide its own
implementation of a function inherited from a base class.
Function overriding is a feature that allows a derived class to
provide a new implementation for a function that is already defined
in its base class. This is essential for building hierarchical
relationships between classes, where derived classes inherit
characteristics and behavior from their base classes but can also
customize or extend those behaviors as needed.
Continue… 80

Class Base {
Public: Virtual Void Display () {
cout<<“here display fun. Of base class “;
}
};
Class Derived: Public Base
{
Public: void Display()
{
cout<<“ display of derived class”;
}
}
81
Syntax:
class Base {
public:
virtual returnType functionName(parameters) {
// Base class implementation
}
};
class Derived : public Base {
public:
returnType functionName(parameters) override {
// Derived class implementation
}
};
Thanks

You might also like