Showing posts with label OOPs. Show all posts
Showing posts with label OOPs. Show all posts

Access Specifiers in C++.

In C++, Access Specifiers or Access Modifiers are keywords used to control the visibility and accessibility of class members (data members and member functions) from outside the class. They are used to implement Data-Hiding concepts in Object Oriented Programming


Let's understand them with one real-life example. Imagine you have a remote-controlled car that has three buttons to perform different things:

  • Public Buttons: These are the big, colorful buttons on the top that anyone can press. They make the car go forward, backward, left, and right. These are public actions that anyone can control.
  • Private Buttons: Inside the remote, some special buttons are hidden. These buttons do things like changing the car's battery or adjusting its internal settings. We don't want just anyone messing with these buttons because it might break the car. Only the person who owns the remote (the car itself) knows about these buttons.
  • Protected Buttons: These are a bit like private buttons, but they can be used by a close friend who has a special key. This friend knows a bit more about how the car works and can use these buttons to customize the car safely.
Similarly, in the programming world, there are three access specifiers: 
  • public. 
  • private.
  • protected.

Let's understand each specifier one by one in detail:

1. Public: Members declared as public are accessible from any part of the program. They have no restrictions on access. Data members and Member Functions which is declared as public can be accessible by different class or function as well. They form the interface of the class, and users can interact with these members freely.

Example Code:

// C++ example to show public access specifier
#include<iostream>
using namespace std;

// define class
class Area{
    // access specifier
    public: 
    int length;
    int breadth;

    int calArea(){
        return length *breadth;
    }
};

int main(){
    Area obj;

    obj.breadth = 5;
    obj.length = 10;

    cout<< "Breadth: " << obj.breadth << endl;
    cout<< "Length: " << obj.length << endl;
    cout << "Aread of Rectangle: " << obj.calArea() << endl;

    return 0;
}
Output:
Breadth: 5
Length: 10
Aread of Rectangle: 50

In the above example, the data member length and breadth are declared as public so we can access and modify their value outside the class.

2. Private: Members declared as private are only accessible within the same class. They are not accessible from outside the class. They are used to encapsulate the internal implementation details of the class.

Example Code:
// C++ example to show private access specifier
#include<iostream>
using namespace std;

// define class
class Area{
    // access specifier
    private: 
    int length;
    int breadth;

    int calArea(){
        return length * breadth;
    }
};

int main(){
    Area obj;
    
    obj.breadth = 5; // Error: privateVar is not accessible
    obj.length = 10; // Error: privateVar is not accessible

    cout<< "Breadth: " << obj.breadth << endl;
    cout<< "Length: " << obj.length << endl;
    cout << "Aread of Rectangle: " << obj.calArea() << endl;

    return 0;
}
Output:
output screenshot for private access specifier

In this above example, the data members and member function are declared as private so we cannot access them outside the class and get the above error.

3. Protected: Members declared as protected are similar to private members but have one additional feature: they can be accessed in the derived classes. They are not accessible from outside the class. They allow derived classes to access certain members while still restricting access to the external world.

Example Code:
//C++ example for protected access specifier
#include <iostream>
using namespace std;

// Base class
class Vehicle {
protected:
    int speed;

public:
    Vehicle() : speed(0) {}

    void setSpeed(int s) {
        speed = s;
        cout << "Setting speed to " << speed << " km/h\n";
    }
};

// Derived class
class Car : public Vehicle {
public:
    void showSpeed() {
        // Derived class can access the protected member 'speed' of the base class
        cout << "Current speed of the car: " << speed << " km/h\n";
    }

    void accelerate() {
        // Derived class can modify the protected member 'speed' of the base class
        speed += 10;
        cout << "Accelerating! New speed: " << speed << " km/h\n";
    }
};

int main() {
    Car myCar;

    // Accessing the public function of the base class
    myCar.setSpeed(60);

    // Accessing the public function of the derived class
    myCar.showSpeed();

    // Accessing a function of the derived class that modifies the protected member of the base class
    myCar.accelerate();
    myCar.showSpeed();

    return 0;
}
Output:
Setting speed to 60 km/h
Current speed of the car: 60 km/h
Accelerating! New speed: 70 km/h
Current speed of the car: 70 km/h

In this example, the Vehicle is the base class, and it has a protected member speed. Car is a derived class from Vehicle. The derived class Car can access and modify the protected member speed of the base class Vehicle.

So I hope you understand the working and use of Access specifiers and their contribution to the principles of encapsulation and data hiding in object-oriented programming.

Classes and Objects in C++.

C++ is an object-oriented programming language, and one of its key features is the ability to create and use classes and objects. Classes and Objects in C++ are the basic building blocks for Object Oriented Programming. In this article, we are going to learn the concept of classes and objects in detail with real-life examples.


What is a Class?

At its core, a class is a blueprint for creating objects. It encapsulates data (attributes) and behaviors (methods), providing a logical structure for organizing and modeling real-world entities. 

Data Members (Attributes): Data members define the attributes of a class, representing its state. They can include fundamental types or other user-defined types.(alert-passed)
Member Functions (Methods): Member functions define the behaviors of a class. They encapsulate operations that can be performed on the class's data.(alert-passed)

SyntaxIn C++, declaring a class involves using the class keyword, followed by the class name and a set of curly braces containing class members.

class ClassName {
    Access Specifier:

    Data Member;

    Member Function();
};


Example: Let's understand with an example, a Car can be represented as a class. A Car class can have attributes (data members) that define its state and behaviors (member functions) that represent its actions. 

class Car {
public: //Access Specifier
    // Attributes
    string brand;
    string model;
    int year;
    bool engineRunning;

    // Member Function to Start the Engine
    void startEngine() {
        if (!engineRunning) {
            cout << "Starting the engine...\n";
            engineRunning = true;
        } else {
            cout << "The engine is already running.\n";
        }
    }
};

What is an Object?

Objects are instances of classes, representing tangible entities in a program. They encapsulate data and behaviors defined by the class, forming the building blocks of C++ applications.

Syntax: Creating an object involves specifying the class name followed by the object name.
ClassName objectName;  // Creating an object

The data member and member function of the class can be accessed using the dot operator with the object name. For example, if your object name is myCar and you want to access the member function startEngine() then you have to write myCar.startEngine() to access that particular function.

Access Specifiers in C++.

Access specifiers control the visibility of class members (data member and member function) from different parts of the program. They are keywords used to define the accessibility or visibility of class members (data members and member functions). 

There are three access specifiers in C++:
  • Public: Members declared as public are accessible from any part of the program. They have no restrictions on access.
  • Private: Members declared as private are only accessible within the same class. They are not accessible from outside the class.
  • Protected: Members declared as protected are similar to private members but have one additional feature: they can be accessed in the derived classes. They are not accessible from outside the class.
Example:
//Access Specifier Example
class AccessExample {
public:
    int publicVar;

private:
    int privateVar;

protected:
    int protectedVar;

public:
    void displayValues() {
        cout << "Public: " << publicVar << "\n";
        cout << "Private: " << privateVar << "\n"; //Err: private is not accessible
        cout << "Protected: " << protectedVar << "\n";
    }
};

Access specifiers provide control over the visibility and accessibility of the class members, contributing to the principles of encapsulation and data hiding in object-oriented programming.

Constructors.

In C++, a constructor is a special member function that is automatically called when an object is created. It has the same name as the class and does not have any return type. The purpose of a constructor is to initialize the object's data members or perform other setup operations when an object is created.

There are two main types of constructors:

Default Constructor:
  • A default constructor is a constructor that takes no parameters.
  • If a class does not have any constructor defined, the compiler automatically generates a default constructor.
  • It initializes the data members with default values (zero or null, depending on the data type).

Parameterized Constructor:
  • A parameterized constructor is a constructor that takes parameters.
  • It allows you to initialize the object with specific values when it is created.
Example:
#include <iostream>

class Car {
private:
    std::string brand;
    int year;

public:
    // Default Constructor
    Car() {
        brand = "Unknown";
        year = 0;
    }

    // Parameterized Constructor
    Car(std::string carBrand, int carYear) {
        brand = carBrand;
        year = carYear;
    }

    void displayInfo() {
        std::cout << "Brand: " << brand << "\n";
        std::cout << "Year: " << year << "\n";
    }
};

int main() {
    // Using Default Constructor
    Car defaultCar;
    defaultCar.displayInfo();

    // Using Parameterized Constructor
    Car customCar("Toyota", 2022);
    customCar.displayInfo();

    return 0;
}
Output:
Brand: Unknown
Year: 0
Brand: Toyota
Year: 2022

In this example, the Car class has a default constructor that initializes the brand and year with default values. It also has a parameterized constructor that allows you to specify the brand and year when creating an object.

Destructor.

In C++, a destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted using the delete keyword. The purpose of a destructor is to release resources or perform cleanup operations before the object is destroyed.

The destructor has the same name as the class, preceded by a tilde (~). Unlike constructors, destructors do not take any parameters, and a class can have only one destructor.

Example:
#include <iostream>

class MyClass {
public:
    // Constructor
    MyClass() {
        std::cout << "Constructor called\n";
    }

    // Destructor
    ~MyClass() {
        std::cout << "Destructor called\n";
    }
};

int main() {
    // Object creation
    MyClass obj; // Constructor called

    // Object goes out of scope
    // Destructor is automatically called here

    return 0;
}
Output:
Constructor called
Destructor called

I hope you understand the basic workings of classes and objects in Object Oriented Programming. There are several key points that you can keep in mind when you are working with classes. 
  • Use access specifiers (public, private, protected) to control the visibility of class members.
  • Always define a constructor and, if needed, a destructor to manage the object's lifecycle.
  • Ensure that all class members are properly initialized, either through default values, member initialization lists, or in the constructor body.
  • Consider making functions const-correct when they do not modify the object's state.
  • Access static members using the class name, not an instance.
  • Prefer composition over inheritance to achieve polymorphic behavior.

30 OOPs Interview Questions and Answer in C++ (2023)

C++ is a powerful programming language known for its extensive use of Object-Oriented Programming (OOP) principles. In the world of software development, mastering OOP concepts is crucial for building scalable, modular, and maintainable code. Whether you're a beginner looking to grasp the fundamentals or an experienced developer aiming to refine your knowledge, this article provides detailed answers to the top 30 OOP interview questions in C++.

30 OOPs Interview Questions and Answer in C++.

1. What is Object-Oriented Programming (OOP)?

Answer: Object-oriented programming is a programming paradigm that uses objects to model real-world entities and organizes code into classes and objects. It promotes the use of concepts like encapsulation, inheritance, and polymorphism to enhance code modularity and reusability.


2. What are the four fundamental principles of OOP?

Answer: The four fundamental principles of OOP are:

  • Encapsulation: This principle bundles data (attributes) and the methods (functions) that operate on that data into a single unit, the class.
  • Abstraction: Abstraction involves hiding complex implementation details and exposing only the necessary features of an object.
  • Inheritance: Inheritance allows a class to inherit properties and behaviors from another class. It promotes code reuse and the creation of a hierarchy of classes.
  • Polymorphism: Polymorphism enables objects of different classes to be treated as objects of a common base class. It includes function overloading and function overriding.

Pillars of Object Oriented Programming

3. What is a class in C++?

Answer: A class in C++ is a blueprint for creating objects. It defines the structure (attributes or properties) and behavior (methods or functions) that objects of that class will have.


4. What is an object in C++?

Answer: An object in C++ is an instance of a class. It represents a specific real-world entity with its own data (attributes) and behavior (methods).

Example:

#include <iostream>

// Define a class named 'Person'
class Person {
public:
    // Public members of the class
    std::string name;
    int age;

    // Member function to introduce the person
    void introduce() {
        std::cout << "I am " << name << " and I am " << age << " years old.";
    }
};

int main() {
    // Create an object of the 'Person' class
    Person person1;

    // Assign values to the object's members
    person1.name = "Alice";
    person1.age = 30;

    // Call the member function to introduce the person
    person1.introduce();

    return 0;
}
Output:
I am Alice and I am 30 years old.

In the above code, we define a class named Person that has two public data members: name and age, and a public member function introduced to introduce the person. In the main function, we create an object of the Person class named persons.


5. What is the difference between a class and an object?

Answer: A class is a template or blueprint for creating objects. It defines the structure and behavior of objects but doesn't occupy memory. An object, on the other hand, is an instance of a class, representing real data and taking up memory.


6. What is Encapsulation in OOP?

Answer: Encapsulation is the principle of bundling data and the methods that operate on that data into a single unit (a class). It provides data hiding, protecting the integrity of an object's data from external access.


7. What is a constructor in C++?

Answer: A constructor in C++ is a special member function of a class that is automatically called when an object of the class is created. It is used for initializing object properties.


8. What is the destructor in C++?

Answer: A destructor in C++ is a special member function that is called when an object goes out of scope or is explicitly destroyed. It's used for cleaning up resources and deallocating memory.


9. What is the "this" pointer in C++?

Answer: The "this" pointer in C++ is a pointer that points to the current instance of an object. It is used within class methods to access the object's members and avoid naming conflicts with local variables.


10. What is inheritance in C++?

Answer: Inheritance is a mechanism in C++ that allows a class to inherit the properties and behaviors of another class. It promotes code reuse and the creation of a hierarchy of classes.


11. Explain the types of inheritance in C++.

Answer: There are several types of inheritance in C++:

  • Single Inheritance: A class inherits from a single base class.
  • Multiple Inheritance: A class can inherit from multiple base classes.
  • Multilevel Inheritance: A class derives from a class that, in turn, derives from another class.
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.


12. What is a base class and a derived class in C++?

Answer: A base class is the class being inherited from, and a derived class is the class that inherits from a base class. The derived class inherits the properties and behaviors of the base class.

  • Base Class: A base class, often referred to as a parent class or superclass, is a class from which other classes (derived classes) inherit properties and behaviors. It serves as a template or blueprint for creating derived classes.
  • Derived Class: A derived class, often referred to as a child class or subclass, is a class that inherits attributes and behaviors from a base class. The derived class extends or specializes the functionality of the base class by adding new attributes and methods or by modifying the inherited ones.


13. What is polymorphism in C++?

Answer: Polymorphism is a key concept in OOP. It allows objects of different classes to be treated as objects of a common base class. There are two main types of polymorphism in object-oriented programming:

1. Compile Time Polymorphism.

Compile Time Polymorphism also known as static binding or early binding occurs at compile time when the program is being compiled. It is achieved through function overloading and operator overloading.

Function Overloading: Function overloading is the ability of a class to have multiple functions with the same name, provided that they have different parameter lists. The appropriate function to call is determined at compile time based on the number and types of arguments passed. (alert-passed)

Example:
// Example of Function overloading in C++
class MathOperations {
public:
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }
};

2. Run Time Polymorphism.

Run Time Polymorphism also known as late binding or dynamic binding occurs at runtime when the program is executed, it is achieved through method overriding, virtual functions, and interfaces/abstract classes.

Method Overriding: Method overriding is the ability of a derived class to provide a specific implementation for a method that is already defined in its base class. The appropriate function to call is determined at runtime, based on the actual type of the object.(alert-passed)

Example:

// Example of Method overriding
class Shape {
public:
    virtual double area() {
        return 0.0; // Base class provides a default implementation
    }
};

class Circle : public Shape {
public:
    double area() override {
        return 3.14 * radius * radius;
    }
};


14. Explain function overloading in C++.

Answer: Function overloading is the ability to define multiple functions with the same name but different parameter lists in the same class. The appropriate function is selected at compile time based on the number and types of arguments.


15. What is function overriding in C++?

Answer: Function overriding is the process of providing a specific implementation for a method defined in a base class. It allows a derived class to provide its own implementation of a method with the same name and parameters as the base class.


16. What is an abstract class in C++?

Answer: An abstract class in C++ is a class that cannot be instantiated. It is typically used as a base class and may contain pure virtual functions, which must be implemented by derived classes.


17. What is a virtual function in C++?

Answer: A virtual function is a member function declared in a base class with the `virtual` keyword. It allows derived classes to provide their own implementations, enabling dynamic binding and polymorphism.


18. What is a pure virtual function in C++?

Answer: A pure virtual function is a virtual function that is declared in a base class but has no implementation.

It is defined with the `= 0` syntax, and derived classes must provide an implementation.


19. What is an interface class in C++?

Answer: C++ doesn't have a built-in "interface" keyword like some other languages. Instead, an interface is often implemented using an abstract base class with pure virtual functions.


20. What is operator overloading in C++?

Answer: Operator overloading allows you to define how C++ operators should work with user-defined types. For example, you can define custom behavior for operators like `+`, `-`, or `==` for your classes.


21. What are the new and delete operators in C++?

Answer: `new` is used to dynamically allocate memory for objects, and `delete` is used to deallocate memory. They are used to manage dynamic memory allocation.


22. What are templates in C++?

Answer: Templates allow you to define generic types and functions that can work with different data types without code duplication. They facilitate code reuse and type safety, especially when working with collections and algorithms.


23. Explain the role of the "friend" keyword in C++.

Answer: The "friend" keyword allows a function or class to access the private and protected members of another class. It promotes encapsulation while providing exceptions.


24. What is a smart pointer in C++?

Answer: A smart pointer is a C++ object that manages the memory allocated for another object. Types include shared_ptr, unique_ptr, and weak_ptr. They help prevent memory leaks and provide automatic memory management.


25. What is the RAII (Resource Acquisition Is Initialization) principle in C++?

Answer: RAII is a programming paradigm where resource management is tied to the lifetime of objects. Resources are acquired in constructors and released in destructors. This principle helps ensure that resources are properly managed and released, even in the presence of exceptions.


26. What is dynamic binding (late binding) in C++?

Answer: Dynamic binding allows the selection of the appropriate function to be delayed until runtime. It enables polymorphism, where the actual function to be called is determined based on the runtime type of an object.


27. What is a vtable in C++?

Answer: A vtable, short for virtual function table, is a data structure used for dynamic dispatch in C++. It maps virtual functions to their implementations. Each class with virtual functions has its own vtable.


28. What is the C++ Standard Template Library (STL)?

Answer: The C++ Standard Template Library (STL) is a set of C++ template classes to provide general-purpose classes and functions with templates to implement many popular and commonly used algorithms and data structures. It includes containers like vectors, maps, and algorithms like sorting and searching.


29. How does C++ handle multiple inheritance, and what is the diamond problem?

Answer: C++ supports multiple inheritance, allowing a class to inherit from multiple base classes. The "diamond problem" occurs when a class inherits from two or more classes that share a common base class. It can lead to ambiguity. To resolve the diamond problem, C++ uses the "virtual" keyword to specify virtual inheritance, ensuring that there's only one shared base class instance.


30. How do you implement an interface in C++?

Answer: In C++, interfaces are implemented using abstract classes with pure virtual functions. A class can derive from the abstract class and must provide implementations for all the pure virtual functions to satisfy the interface requirements.


These detailed answers should help you prepare for C++ OOP interviews by better understanding the concepts and principles involved.

Object Oriented Programming in C++.

Object-Oriented Programming (OOP) is a programming paradigm that organizes and structures code around the concept of "objects," which are self-contained units containing both data and behavior. In OOP, objects represent real-world entities, and the programming revolves around interactions between these objects.


The core principles of Object-Oriented Programming are:

  • Encapsulation.
  • Abstraction.
  • Inheritance.
  • Polymorphism.
We are going to cover all these principles in detail with real-life examples in this post but before understanding them there are a few important terms that we need to understand. 

Class

In C++, a class is a user-defined data type that serves as a blueprint for creating objects. It encapsulates data (attributes) and methods (member functions) that operate on that data. Classes enable developers to model real-world entities, organize code, and implement the principles of Object-Oriented Programming (OOP).

Object

In C++, an object is a concrete instance of a class. It is a self-contained unit that combines data (attributes) and behavior (methods) defined in the class blueprint. Objects represent real-world entities and can interact with each other through their methods and attributes.

Let's take a real-world example to understand the concept of class and object and how it works.

Example: Consider we have a class name Vehicle, the Vehicle class contains attributes like Brand, Model, Color, and Fuel Type. It also has some properties like ChangeGear(), GetFuelLevel(), Accelerate(), and Brake(). Using this Vehicle class as a blueprint, we can create multiple vehicle objects, each with its own unique set of attributes and behavior. 

C++ Example Code:
//C++ Example Code to show working of Class and Objects
#include <iostream>
#include <string>
using namespace std;

class Car {
public:
    // Attributes
    string brand;
    string model;
    string color;
    string fuelType;

    // Methods
    void ChangeGear() {
        cout << "The " << brand << " " << model << " is changing Gear...\n";
    }

    void Accelerate() {
        cout << "The " << brand << " " << model << " is accelerating...\n";
    }

    void Brake() {
        cout << "The " << brand << " " << model << " is braking...\n";
    }
};

int main() {
    // Creating car objects using the Car class
    Car car1;

    car1.brand = "Toyota";
    car1.model = "Camry";
    car1.color = "Blue";
    car1.fuelType = "Petrol";

    car1.ChangeGear();
    car1.Accelerate();
    car1.Brake();

    return 0;
}
Output:
The Toyota Camry is changing Gear...
The Toyota Camry is accelerating...
The Toyota Camry is braking...
The memory required to hold the object's data (attributes) and the code for its methods (member functions) is allocated from the computer's memory.(alert-success)

I hope till now you have understood the two most important terms of OOPs that is class and object. Now we are going to explore the core principles of OOPs one by one.


Encapsulation

Encapsulation is the concept of bundling data and methods within a class, hiding internal implementation details from the outside world. It allows for data abstraction and provides access control through public, private, and protected access specifiers. You can read more about Access Specifiers here.


Example: In the Car class, the attributes (make, model, year) may be declared as private, ensuring that they can only be accessed and modified through public methods like getMake() and setMake(). This way, the internal state of the car object is encapsulated and protected.


Example Code:

#include <iostream>
#include <string>
using namespace std;

class Car {
private:
    string make;
    string model;
    int year;

public:
    // Constructor
    Car(string carMake, string carModel, int carYear) {
        make = carMake;
        model = carModel;
        year = carYear;
    }

    // Getter methods
    string getMake() const {
        return make;
    }
    string getModel() const {
        return model;
    }
    int getYear() const {
        return year;
    }

    // Setter methods
    void setMake(string newMake) {
        make = newMake;
    }
    void setModel(string newModel) {
        model = newModel;
    }
    void setYear(int newYear) {
        year = newYear;
    }
};

int main() {
    // Creating a Car object using the constructor
    Car myCar("Toyota", "Camry", 2022);

    // Using the setter methods to modify attributes
    myCar.setMake("Honda");
    myCar.setModel("Civic");
    myCar.setYear(2021);

    // Displaying the updated car details
    cout << "\nUpdated Car Details:" << endl;
    cout << "Make: " << myCar.getMake() << endl;
    cout << "Model: " << myCar.getModel() << endl;
    cout << "Year: " << myCar.getYear() << endl;

    return 0;
}
Output:
Updated Car Details:
Make: Honda
Model: Civic
Year: 2021

Access specifiers are keywords used in class definitions to control the visibility and accessibility of class members (attributes and methods) from outside the class. (alert-success) 


Abstraction

Abstraction involves representing essential features and behavior of objects while hiding unnecessary details. It allows us to focus on what an object does rather than how it does it.

Abstraction is achieved in C++ through the use of classes and access specifiers (public, private, protected). The public interface of the class represents the abstraction, while the private and protected sections hide the implementation details from external code. 

Example: In a banking application, a BankAccount class may provide methods like deposit(), withdraw(), and getBalance(), abstracting away the complex internal banking operations and exposing only the essential functionality needed by users.


Inheritance

Inheritance is a mechanism that allows a class to inherit properties and behaviors from another class, forming a hierarchical relationship. The derived class (child class) inherits the characteristics of the base class (parent class).
Inheritance allows for code reuse, as the derived class can reuse the properties and behaviors of the base class, eliminating the need to rewrite common code.(alert-success)

They are classified into various types based on the hierarchy and relationships between classes and these are:

  • Single Inheritance: A derived class inherits from only one base class. 
  • Multiple Inheritance: A derived class can inherit from two or more base classes.
  • Multilevel Inheritance: A derived class inherits from another derived class, creating a chain of inheritance.
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  • Hybrid (or Virtual) Inheritance: A combination of multiple and multilevel inheritance.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables the same method to be implemented in different ways in different classes, based on their specific behavior.

Example: Using the vehicle hierarchy, a generic method like drive() can be defined in the base class Vehicle. Each derived class (Car, Motorcycle, Truck) can provide its own implementation of the drive() method based on the unique way each vehicle type operates.

Difference Between Structure and Class in C++

structure and class difference

In C++, both structures and classes are used to define custom data types that can hold multiple data members and member functions. While they share some similarities, there are a few key differences between structures and classes. Here in this article, we are going to understand the key differences between them and which one we should use in which conditions. But before discussing the difference we should have the basic idea of structure and class in C++.


What is Structure in C++?

In C++, a structure is a user-defined data type that allows you to group related data elements together. It provides a way to create a composite data structure that can hold multiple variables of different types. 


Structure Syntax:

struct StructureName {
    // Member declarations
    DataType1 member1;
    DataType2 member2;
    // ...
};

The struct keyword is used to define a structure and StructureName is the name given to the structure. Inside the curly braces {} you declare the member of the structure.

What is Class in C++?

In C++, a class is a user-defined data type that encapsulates data and functions together. It provides a blueprint for creating objects and defines their behavior and properties.

Class Syntax:
class ClassName {
    // Member declarations
    AccessSpecifier1:
        DataType1 member1;
        DataType2 member2;
        // ...

    AccessSpecifier2:
        FunctionReturnType functionName1(ParameterList);
        FunctionReturnType functionName2(ParameterList);
        // ...
};

The class keyword is used to define a Class and the ClassName is the name given to the class. Inside the curly braces {}, you declare the members of the class. Members can include data members (variables) and member functions (methods). AccessSpecifier is to determine the accessibility of the members within the class.  

Difference Between Structure and Class.

While they have some similarities, there are a few key differences between structures and classes and we are going to discuss each of them in detail.

Structure Class
Members are public by default. Members are private by default.
Structure does not support inheritance. A class supports single and multiple inheritances.
Does not have access specifiers (private, protected). Access specifiers can be used (public, private, protected).
A structure cannot have member functions. A class can have member functions.
A structure cannot have constructors or destructors. A class can have constructors and destructors.
Memory is allocated for each instance separately. Memory is allocated once and shared among instances.
Used for simple data structures or data containers. Used for complex objects with behavior and properties.

1. Default Member Accessibility.

In a structure, by default, all members (data and functions) are public. This means that they can be accessed from outside the structure without any restrictions. 

C++ Structure Example Code:
//C++ code Structure default Accessibility
#include <iostream>
using namespace std;

// Define a structure named Point
struct Point {
    int x;
    int y;
};

int main() {
    // Declare a variable of type Point
    Point p1;

    // Access and assign values to the members
    p1.x = 10;
    p1.y = 20;

    // Display the values of the members
    cout << "x: " << p1.x << endl;
    cout << "y: " << p1.y << endl;

    return 0;
}
Output:
x: 10
y: 20

In contrast, in a class, by default, all members are private. This means that they can only be accessed within the class itself and its friend functions.

C++ Class Example Code:
//C++ code class defualt Accessibility
#include <iostream>
using namespace std;

// Define a class named Point
class Point {
    //private by default
    int x;
    int y;
};

int main() {
    // Declare a variable of type Point
    Point p1;

    //Error because members are private
    p1.x = 10;
    p1.y = 20;

    // Display the values of the members
    cout << "x: " << p1.x << endl;
    cout << "y: " << p1.y << endl;

    return 0;
}
Output:

2. Inheritance.

In C++, classes support inheritance, which is the ability to derive new classes from existing ones. Inheritance allows for code reuse and the creation of hierarchical relationships between classes. Structures, on the other hand, do not support inheritance by default. Although you can technically use inheritance with structures, it is more common to use classes for that purpose.

3. Object-Oriented Features.

Classes are primarily used in object-oriented programming (OOP) and provide features like encapsulation, data hiding, and polymorphism. They are suitable for creating complex data types with associated behaviors. Structures, on the other hand, are traditionally used for simple data structures that group related data together. They do not support advanced OOP features like inheritance and access specifiers.

When to use Structure in C++?

  • When you need a simple data container to group related data together, such as representing a point with x and y coordinates.
  • When you want all members to be public by default, without the need for strict encapsulation.
  • When you don't need to use advanced OOP features like inheritance and access specifiers.

When to use Class in C++?

  • When you want to create complex data types with associated behaviors and encapsulation.
  • When you need to define private members and provide controlled access through member functions.
  • When you want to use inheritance to derive new classes and establish hierarchical relationships.

It's important to note that while structures and classes have some differences in their default behavior, you can often achieve similar functionality using either of them.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson