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
    CSI-312
    Progress0 / 16 topics
    Topics
    1. Evolution of Object-Oriented (OO) Programming2. Object-Oriented (OO) Concepts and Principles3. Problem Solving in OO Paradigm4. OO Programme Design Process5. Classes6. Methods7. Objects and Encapsulation8. Constructors and Destructors9. Operator Overloading10. Function Overloading11. Virtual Functions12. Derived Classes13. Inheritance14. Polymorphism15. I/O and File Processing16. Exception Handling
    CSI-312›Classes
    Object Oriented ProgrammingTopic 5 of 16

    Classes

    8 minread
    1,286words
    Intermediatelevel

    Classes in Object-Oriented Programming (OOP)

    A class is one of the fundamental building blocks in object-oriented programming. It acts as a blueprint for creating objects (instances), defining their attributes (data) and behaviors (methods or functions). Classes allow you to encapsulate data and functions in a logical, organized structure, making your code more reusable, maintainable, and scalable.


    Key Concepts of Classes

    1. Class Definition:

      • A class is defined using the class keyword (in languages like C++, Python, Java, etc.).
      • It contains:
        • Attributes (or fields): Variables that hold data related to the object.
        • Methods (or functions): Functions that define behaviors or actions the object can perform.
        • Constructors: Special methods used to initialize an object when it is created.
    2. Object:

      • An object is an instance of a class. When a class is defined, no memory is allocated until you create an object from that class.
      • Each object created from the class has its own set of attribute values, but shares the methods of the class.
    3. Access Modifiers:

      • Public: Members are accessible from outside the class.
      • Private: Members are not accessible from outside the class, providing encapsulation.
      • Protected: Members are accessible by the class itself, and by derived (child) classes.
    4. Encapsulation:

      • Encapsulation refers to bundling the data (attributes) and the methods (functions) that operate on the data within a class. This hides the internal state and only exposes selected parts of the object’s functionality, typically through getter and setter methods.

    Class Structure in C++

    Here’s a breakdown of the structure of a class in C++:

    #include <iostream>
    using namespace std;
    
    // Class Definition
    class Car {
    private: // Private members (cannot be accessed directly outside the class)
        string model;
        int year;
    
    public:  // Public members (can be accessed from outside the class)
        // Constructor to initialize an object
        Car(string m, int y) {
            model = m;
            year = y;
        }
    
        // Method to display car information
        void displayInfo() {
            cout << "Model: " << model << endl;
            cout << "Year: " << year << endl;
        }
    
        // Getter method for 'model'
        string getModel() {
            return model;
        }
    
        // Setter method for 'model'
        void setModel(string m) {
            model = m;
        }
    };
    
    int main() {
        // Create an object of the class 'Car'
        Car myCar("Toyota Camry", 2020);
    
        // Accessing a public method
        myCar.displayInfo();
        
        // Using getter and setter methods
        cout << "Current Model: " << myCar.getModel() << endl;
        myCar.setModel("Honda Civic");
        cout << "Updated Model: " << myCar.getModel() << endl;
    
        return 0;
    }
    

    Explanation of the Code:

    • Class Definition:

      • The class Car contains two private attributes (model, year) and several public methods.
      • The constructor Car(string m, int y) initializes the model and year attributes when an object is created.
      • The displayInfo() method prints the car's details.
      • getModel() and setModel() are getter and setter methods to access and modify the model attribute.
    • Creating Objects:

      • In the main function, the object myCar is created using the constructor with the model "Toyota Camry" and year 2020.
      • The displayInfo() method is called to print the car's details.
      • The getModel() and setModel() methods are used to access and update the model of the car.

    Types of Methods in Classes

    1. Instance Methods:

      • These are regular methods that operate on the instance of the class (i.e., the object).
      • They can access and modify the attributes of the class.
    2. Static Methods:

      • A static method is a method that belongs to the class itself rather than to instances of the class.
      • Static methods can only access static members of the class, not instance attributes or methods.

      Example (C++):

      class Car {
      private:
          static int carCount;  // Static variable to keep track of the number of cars
      
      public:
          Car() {
              carCount++;
          }
      
          static int getCarCount() {  // Static method to access the static variable
              return carCount;
          }
      };
      
      int Car::carCount = 0;  // Initialize static variable
      
      int main() {
          Car car1;
          Car car2;
          cout << "Total cars: " << Car::getCarCount() << endl;  // Access static method
          return 0;
      }
      
    3. Constructors and Destructors:

      • Constructor: Special method called when an object is created. Its purpose is to initialize the object.
      • Destructor: Special method called when an object is destroyed. It is typically used for cleanup (e.g., deallocating memory).

      Example:

      class Car {
      private:
          string model;
          int year;
      
      public:
          // Constructor to initialize the Car object
          Car(string m, int y) {
              model = m;
              year = y;
              cout << "Car object created: " << model << endl;
          }
      
          // Destructor to clean up resources
          ~Car() {
              cout << "Car object destroyed: " << model << endl;
          }
      };
      
      int main() {
          Car myCar("Tesla", 2023);
          // The destructor will be automatically called when myCar goes out of scope
      }
      

    Inheritance and Extending Classes

    In OOP, inheritance allows you to create a new class based on an existing class. The new class (child or subclass) inherits the attributes and methods of the existing class (parent or superclass), but can also have its own additional attributes and methods.

    Example (Inheritance in C++):

    #include <iostream>
    using namespace std;
    
    // Base Class
    class Vehicle {
    public:
        void start() {
            cout << "Vehicle is starting." << endl;
        }
    };
    
    // Derived Class
    class Car : public Vehicle {
    public:
        void drive() {
            cout << "Car is driving." << endl;
        }
    };
    
    int main() {
        Car myCar;
        myCar.start();  // Inherited from Vehicle class
        myCar.drive();  // Defined in Car class
        return 0;
    }
    
    • The class Car inherits from Vehicle and can use the start() method from the parent class, as well as its own drive() method.
    • The public keyword in class Car : public Vehicle indicates that the Vehicle class's public members are accessible to the Car class.

    Polymorphism in Classes

    Polymorphism allows objects of different classes to be treated as objects of a common superclass. It can be implemented in two ways:

    1. Compile-time polymorphism (Method Overloading or Operator Overloading).
    2. Runtime polymorphism (Method Overriding using virtual functions).

    Example (Runtime Polymorphism with Virtual Functions):

    #include <iostream>
    using namespace std;
    
    class Animal {
    public:
        virtual void sound() { // Virtual function for dynamic binding
            cout << "Some generic animal sound" << endl;
        }
    };
    
    class Dog : public Animal {
    public:
        void sound() override {  // Overriding the base class method
            cout << "Bark!" << endl;
        }
    };
    
    int main() {
        Animal* animal = new Dog();  // Pointer of base class type pointing to derived class object
        animal->sound();  // Calls the Dog class's sound method (runtime polymorphism)
        delete animal;
        return 0;
    }
    
    • In this example, sound() is a virtual function in the base class Animal. When it is overridden in the Dog class, the runtime polymorphism ensures that the sound() method of the Dog class is called, even though the pointer is of type Animal.

    Conclusion

    A class in OOP is a powerful tool for organizing and structuring code in a way that mimics real-world entities and their interactions. By using classes, you can:

    • Define attributes and behaviors for objects.
    • Use encapsulation to protect data and ensure controlled access.
    • Create objects that can inherit behaviors from other classes, extending and overriding functionality as needed.
    • Implement polymorphism to handle different object types using a common interface.

    By adhering to these principles, classes enable developers to create modular, reusable, and maintainable code that is easier to manage and scale.

    Previous topic 4
    OO Programme Design Process
    Next topic 6
    Methods

    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 time8 min
      Word count1,286
      Code examples0
      DifficultyIntermediate