0% found this document useful (0 votes)
28 views6 pages

CPP Unit1

The document provides an overview of pointers and virtual functions in C++. It explains how pointers work, including the use of the 'this' pointer and the relationship between base and derived class pointers. Additionally, it covers the concept of virtual functions, pure virtual functions, and abstract classes, emphasizing their importance in achieving runtime polymorphism and defining interfaces in C++.

Uploaded by

rohitpatilno.1
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)
28 views6 pages

CPP Unit1

The document provides an overview of pointers and virtual functions in C++. It explains how pointers work, including the use of the 'this' pointer and the relationship between base and derived class pointers. Additionally, it covers the concept of virtual functions, pure virtual functions, and abstract classes, emphasizing their importance in achieving runtime polymorphism and defining interfaces in C++.

Uploaded by

rohitpatilno.1
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/ 6

Unit-1 Pointer and Virtual Function

Pointer
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well
as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is
one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer variable that points to the same data
type (such as an int or string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

How to use a pointer?


• Define a pointer variable
• Assigning the address of a variable to a pointer using the unary operator (&) which returns the address
of that variable.
• Accessing the value stored in the address using unary operator (*) which returns the value of the
variable located at the address specified by its operand.
#include <iostream.h>
using namespace std;
void geeks()
{
int var = 20; // declare pointer variable
int* ptr; // note that data type of ptr and var must be same
ptr = &var; // assign the address of a variable to a pointer
cout << "Value at ptr = " << ptr << "\n";
cout << "Value at var = " << var << "\n";
cout << "Value at *ptr = " << *ptr << "\n";
}
// Driver program
int main()
{
geeks();
return 0;
}

//Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20
This Pointer
Every object in C++ has access to its own address through an important pointer called this pointer. The this
pointer is an implicit parameter for all member functions. Therefore, inside a member function, this may be used
to refer to the invoking object.
Friend functions do not have a this pointer because friends are not members of a class. Only member functions
have this pointer

#include <iostream.h>
#include <conio.h>
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}

C++ allows base class pointers to point to derived class objects.


• Let we have class base { … }; class derived : public base { … };
Then we can write:
base *p1;
derived d_obj;
p1 = &d_obj;
class Base {
public:
void show() {
cout << “base\n”;
}
};
class Derv1 : public base {
public:
void show() {
cout << “derived1\n”;
}
class Derv2 : public base {
public:
void show() {
cout << “derived2\n”;
}
};
void main()
{
Derv1 dv1;
Derv2 dv2;
Base *ptr
ptr = &dv1;
ptr->show();
ptr = &dv2;
ptr ->show();
getch();
}

Pointer to Derived Class Object


A pointer is a data type that stores the address of other data types. Pointers can be used for base objects as
well as objects of derived classes. A pointer to the object of the derived class and a pointer to the object of the
base class are type-compatible (may be used in different ways).

Approach:
• A derived class is a class that takes some properties from its base class.
• It is true that a pointer of one class can point to another class, but classes must be a base and derived
class, then it is possible.
• To access the variable of the base class, a base class pointer will be used.
• So, a pointer is a type of base class, and it can access all, public function and variables of the base class
since the pointer is of the base class, this is known as a binding pointer.
• In this pointer base class is owned by the base class but points to the derived class object.
• The same works with derived class pointer, values are changed.

Virtual function

A virtual function (also known as virtual methods) is a member function that is declared within a base class and
is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and execute the derived class’s version
of the method.

• Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for the function call.
• They are mainly used to achieve Runtime polymorphism.
• Functions are declared with a virtual keyword in a base class.
• The resolving of a function call is done at runtime.
Rules for Virtual Functions
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using a pointer or reference of base class type to achieve runtime
polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the derived class.
5. They are always defined in the base class and overridden in a derived class. It is not mandatory for the
derived class to override (or re-define the virtual function), in that case, the base class version of the
function is used.
6. A class may have a virtual destructor but it cannot have a virtual constructor.

#include <iostream>
using namespace std;

class base {
public:
virtual void print() { cout << "print base class\n"; }

void show() { cout << "show base class\n"; }


};

class derived : public base {


public:
void print() { cout << "print derived class\n"; }

void show() { cout << "show derived class\n"; }


};

int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}

Pure Virtual Functions

A pure virtual function (or abstract function) in C++ is a virtual function for which we can have an
implementation, But we must override that function in the derived class, otherwise, the derived class will also
become an abstract class. A pure virtual function is declared by assigning 0 in the declaration.

#include <iostream>
using namespace std;
// Abstract Base Class
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;
// Virtual destructor (recommended for polymorphic base classes)
virtual ~Shape() {}
};
class Circle : public Shape {
public:
// Providing implementation for pure virtual function
void draw() override {
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
public:
// Providing implementation for pure virtual function
void draw() override {
cout << "Drawing Rectangle" << endl;
}
};
int main() {
// Shape s; // Error: cannot instantiate abstract class
Shape* shape1 = new Circle();
Shape* shape2 = new Rectangle();

shape1->draw(); // Calls Circle::draw()


shape2->draw(); // Calls Rectangle::draw()
delete shape1;
delete shape2;
return 0;
}

Abstract Class in C++

An abstract class in C++ is a class that cannot be instantiated directly. It is designed to serve as a base
class for other classes and typically contains one or more pure virtual functions. Pure virtual functions
define an interface that derived classes must implement.

Key Points:

• Definition:
A class becomes abstract if it contains at least one pure virtual function, declared by assigning =
0 to the function declaration.
• Purpose:
Abstract classes provide a common interface for derived classes, ensuring that certain methods
are implemented by all subclasses. They enable polymorphism, allowing you to manipulate
objects of different types through pointers or references to the abstract base class.
• Instantiation:
You cannot create an object of an abstract class directly. Instead, you instantiate objects of
derived classes that implement all pure virtual functions.
• Usage:
Abstract classes are often used to define interfaces and enforce a contract for derived classes,
promoting consistency and reusability in code.

#include <iostream>
using namespace std;
// Abstract class with a pure virtual function
class Shape {
public:
// Pure virtual function makes Shape an abstract class
virtual void draw() = 0;
// Virtual destructor for proper cleanup of derived class objects
virtual ~Shape() {}
};
class Circle : public Shape {
public:
// Overriding the pure virtual function
void draw() override {
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
public:
// Overriding the pure virtual function
void draw() override {
cout << "Drawing Rectangle" << endl;
}
};
int main() {
// Shape s; // Error: Cannot instantiate abstract class
Shape* shape1 = new Circle();
Shape* shape2 = new Rectangle();
shape1->draw(); // Output: Drawing Circle
shape2->draw(); // Output: Drawing Rectangle
delete shape1;
delete shape2;
return 0;
}

You might also like