Complete-Preparation

๐ŸŽ‰ One-stop destination for all your technical interview Preparation ๐ŸŽ‰

View the Project on GitHub

Introduction to OOPs

Definition

Object-Oriented Programming is basically a programming style that we used to follow in modern programming. It primarily revolves around classes and objects. Object-Oriented programming or OOPs refers to the language that uses the concept of class and object in programming.

Class

A class is a logical entity used to define a new data type. A class is a user-defined type that describes what a particular kind of object will look like. Thus, a class is a template or blueprint for an object. A class contains variables, methods, and constructors.

Syntax:

class class_name {
    // class body
    // properties 1
    // methods
};

Object

An object is an instance of a Class. It is an identifiable entity with some characteristics and behavior. Objects are the basic units of object-oriented programming. It may be any real-world object like a person, chair, table, pen, animal, car, etc.

Syntax to create an object in C++:

    class_name objectName;

Syntax to create an object dynamically in C++:

    class_name * objectName = new class_name();

The classโ€™s default constructor is called, and it dynamically allocates memory for one object of the class. The address of the memory allocated is assigned to the pointer, i.e., objectName.

Creating a class Animal and objects mammal, amphibian and bird:

// creating Animal class
class Animal {
public:
    bool gives_birth;
    bool lay_egg;
    bool live_in_ground;
    bool live_in_water;
    bool have_wings;
};

int main()
{
    // creating an object of animal class
    Animal mammal;
    mammal.gives_birth = true;
    mammal.lay_egg = false;
    mammal.live_in_ground = true;
    mammal.live_in_water = false;
    mammal.have_wings = false;

    Animal amphibian;
    amphibian.gives_birth = false;
    amphibian.lay_egg = true;
    amphibian.live_in_ground = true;
    amphibian.live_in_water = true;
    amphibian.have_wings = false;

    Animal bird;
    bird.gives_birth = false;
    bird.lay_egg = true;
    bird.live_in_ground = true;
    bird.live_in_water = false;
    bird.have_wings = true;
}

Features of OOPs:

Four major object-oriented programming features make them different from non-OOP languages:

Need of object-oriented programming?

Resource