ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Classes and Objects
    Object Oriented ProgrammingTopic 3 of 24

    Classes and Objects

    7 minread
    1,115words
    Intermediatelevel

    Classes and Objects in Object-Oriented Programming (OOP)

    In Object-Oriented Programming (OOP), classes and objects are fundamental concepts. They form the core of OOP by allowing the modeling of real-world entities and behaviors within a program. Let’s go over both of these concepts in detail.


    Classes

    A class is essentially a blueprint or a template for creating objects. It defines a type of object that includes both data and methods that operate on that data. The class is a logical entity that describes the attributes and behaviors common to all objects of that type.

    Key Components of a Class:

    1. Data Members (Attributes):

      • These are variables that hold the state or properties of an object.
      • Data members represent characteristics of the object.
    2. Member Functions (Methods or Behaviors):

      • These are functions defined within the class that describe the behaviors of the object. These methods can access and modify the data members of the class.
      • Member functions can be called on objects of that class.
    3. Access Modifiers:

      • Access modifiers control the accessibility of the data members and member functions. Common access modifiers include:
        • public: Members can be accessed from anywhere.
        • private: Members can only be accessed within the class.
        • protected: Members can be accessed within the class and by derived classes.
    4. Constructor:

      • A special function used to initialize an object when it is created. Constructors can be default (with no parameters) or parameterized (with arguments to initialize the object with specific values).
    5. Destructor:

      • A special function used to clean up and release resources when an object is destroyed.

    Example of a Class in C++:

    #include <iostream>
    using namespace std;
    
    // Define the class
    class Car {
    private:
        string brand;   // Data member
        int speed;      // Data member
    
    public:
        // Constructor to initialize the object
        Car(string b, int s) {
            brand = b;
            speed = s;
        }
    
        // Method to display car details
        void displayDetails() {
            cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
        }
    
        // Method to accelerate the car
        void accelerate() {
            speed += 10;
            cout << "The car accelerates. New speed: " << speed << " km/h" << endl;
        }
    
        // Method to brake the car
        void brake() {
            speed -= 10;
            cout << "The car slows down. New speed: " << speed << " km/h" << endl;
        }
    };
    
    // Main function to create objects and call methods
    int main() {
        Car myCar("Toyota", 100);  // Create an object of the class
        myCar.displayDetails();    // Call method to display car details
        myCar.accelerate();        // Call method to accelerate the car
        myCar.brake();             // Call method to brake the car
        return 0;
    }
    

    In the example above:

    • Car is the class.
    • brand and speed are the data members.
    • displayDetails(), accelerate(), and brake() are the member functions that define the behavior of the Car object.
    • The constructor Car(string b, int s) initializes the Car object with specific brand and speed values when an object is created.

    Objects

    An object is an instance of a class. When a class is defined, it serves as a template, and an object is created from that template. Objects hold the data (state) defined by the class and provide the behavior (methods) described by the class.

    Key Points About Objects:

    1. Instantiation:

      • An object is created by instantiating a class. This means allocating memory for the object and initializing its data members.
      • In C++, objects can be created using the class name followed by the object name.
      • Example: Car myCar("Toyota", 100); creates an object myCar of type Car.
    2. State:

      • The state of an object refers to the values stored in its data members at any given point in time. Each object can have its own state.
    3. Behavior:

      • The behavior of an object is defined by the member functions (methods) of the class. Each object can perform actions defined in these methods.

    Example of Creating and Using Objects:

    #include <iostream>
    using namespace std;
    
    class Book {
    private:
        string title;
        string author;
    
    public:
        // Constructor to initialize Book object
        Book(string t, string a) {
            title = t;
            author = a;
        }
    
        // Method to display book details
        void displayInfo() {
            cout << "Title: " << title << ", Author: " << author << endl;
        }
    };
    
    int main() {
        // Creating objects of the class Book
        Book myBook1("1984", "George Orwell");
        Book myBook2("To Kill a Mockingbird", "Harper Lee");
    
        // Calling methods on objects
        myBook1.displayInfo();
        myBook2.displayInfo();
    
        return 0;
    }
    

    In this example:

    • Book is the class.
    • myBook1 and myBook2 are objects of type Book. They each have their own state (title and author).
    • The method displayInfo() is called on both objects to display their details.

    Object Creation:

    Objects are created in two common ways:

    1. Automatic (Local) Object:

      • When you create an object in the local scope, the object is automatically destroyed when it goes out of scope.
      • Example: Book myBook("1984", "George Orwell");
    2. Dynamic (Heap) Object:

      • When you create an object dynamically (using new in C++), the object persists until it is explicitly destroyed using delete.
      • Example: Book* myBook = new Book("1984", "George Orwell");
      • Don't forget to use delete to free the dynamically allocated memory.

    Relationship Between Classes and Objects

    • A class is the definition or blueprint of an object, while an object is an instance of a class.
    • A class defines what attributes (data members) and behaviors (methods) its objects will have, while an object holds actual values for those attributes and can call the methods.

    Real-World Example of Classes and Objects:

    Imagine modeling a Library System. You might have a Book class:

    • Class Book could define data members like title, author, ISBN, and methods like borrow() or returnBook().
    • Objects of the Book class could represent individual books in the library, each with its own title, author, and other attributes.

    Summary of Classes and Objects

    • Class: A blueprint or template for creating objects, which defines attributes and behaviors.
    • Object: An instance of a class that holds actual data and performs actions based on the methods defined in the class.
    • Classes define what objects of that type will look like, and objects are created based on those definitions to store data and interact with other objects.

    Understanding the concepts of classes and objects is essential to mastering Object-Oriented Programming, as they allow for the organization of complex systems in a modular and reusable way.

    Previous topic 2
    Object-Oriented Programming: Terminology and Features
    Next topic 4
    Data Encapsulation

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,115
      Code examples0
      DifficultyIntermediate