Key Features of OOP
- Encapsulation: Binding Data & methods that operate on data together in a single unit is called Encapsulation. This is achieved through the use of Classes & Objects.
- Abstraction: Hiding unnecessary implementation details from the outer world and showing only important usable details of an object is called Abstraction. This is achieved through the use of access modifiers – public, private & protected.
- Inheritance: A Class can inherit properties & methods from another class using Inheritance. The subclass can inherit properties and methods from a class (base class) and then either add more properties/methods or redefine existing methods of the base class.
- Polymorphism: The term “Polymorphism” means many forms. In OOP, it refers to superclass & subclass having the same method names but different implementations or parameters.
Unique OOP Features in C++
These are the OOP features provided by C++, which are provided by only a few other or no other programming languages.
- Multiple Inheritance – allows a class to inherit from multiple base classes.
- Virtual Functions & Virtual Inheritance
- Operator Overloading
- Friend Functions & Friend Classes
- C++ Syntax for Object-Oriented Programming
- Explicit Destruction
C++ Syntax for Object-Oriented Programming
Class Declaration
ClassName {
// Access specifiers (public, private, protected)
public:
// Member variables
// Member functions (methods)
private:
// Member variables
// Member functions (methods)
protected:
// Member variables
// Member functions (methods)
};
Object Creation / Instantiating a Class
ClassName objectName; // direct way
ClassName *objectPointer = new ClassName(); // using pointer
Constructor
ClassName(); // Default constructor
ClassName(type param); // Parameterized constructor
Destructor
~ClassName();
Accessing Objects
ObjectName.property;
ObjectName.method();
ObjectPointer->property;
ObjectPointer->method();
Inheritance
class DerivedClass : accessSpecifier BaseClass {
// Body of derived class
};
Multiple Inheritance
class DerivedClass : accessSpecifier BaseClass1, accessSpecifier BaseClass2 {
// Body of derived class
};
Member Function Declaration
returnType functionName(parameters);
Static Members
static dataType variableName;
static returnType functionName(parameters);
Function Overloading
returnType functionName(parameters);
returnType functionName(different_parameters);
Operator Overloading
returnType operator symbol(parameters);
Virtual Function
virtual returnType functionName(parameters);