Tutorial in C++
Tutorial in C++
Tutorial in C++
Kanishk Tomar
23BCE10588
source code.
#include <iostream>
class Complex {
private:
float real;
float imag;
public:
// Constructor
cout << real << " + " << imag << "i" << endl;
};
int main() {
return 0;
In C++, polymorphism allows functions to behave differently based on the object that invokes them.
Virtual functions enable late binding, and pure virtual functions define an interface in a base class
that derived classes must implement.
Virtual Function: A virtual function is a member function in a base class that you expect to override
in derived classes. When you refer to a derived object using a pointer or reference to the base class,
you can call a virtual function to execute the derived class’s version of that function.
Pure Virtual Function: A pure virtual function is a virtual function that has no implementation in the
base class. It is declared by assigning 0 to the function in the base class. A class containing a pure
virtual function is abstract and cannot be instantiated.
#include <iostream>
// Base class
class Shape {
public:
// Virtual function
// Derived class 1
public:
};
// Derived class 2
public:
};
int main() {
delete s1;
delete s2;
return 0;
Inheritance allows one class to inherit properties and behaviors (methods) from another class. There
are several types of inheritance in C++:
a. Single Inheritance
#include <iostream>
// Base class
class Animal {
public:
void eat() {
};
// Derived class
public:
void bark() {
};
int main() {
Dog d;
return 0;
b. Multiple Inheritance
#include <iostream>
// Base class 1
class A {
public:
void showA() {
};
// Base class 2
class B {
public:
void showB() {
};
// Derived class
public:
void showC() {
};
int main() {
C c;
c.showC(); // Defined in C
return 0;
c. Multilevel Inheritance
#include <iostream>
// Base class
class A {
public:
void showA() {
}
};
// Derived class 1
class B : public A {
public:
void showB() {
};
// Derived class 2
class C : public B {
public:
void showC() {
};
int main() {
C c;
c.showC(); // Defined in C
return 0;