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›Methods
    Object Oriented ProgrammingTopic 6 of 16

    Methods

    8 minread
    1,394words
    Intermediatelevel

    Methods in Object-Oriented Programming (OOP)

    In Object-Oriented Programming (OOP), methods are functions that define the behaviors or actions that objects of a class can perform. They are typically used to manipulate or interact with an object's data (its attributes), or to provide functionality related to the object's behavior. Methods are defined inside classes and can operate on the object's internal state, or on external data passed to them.

    Key Aspects of Methods

    1. Instance Methods:

      • Instance methods are functions that belong to individual objects (instances) of a class.
      • They can access and modify the object's attributes (instance variables).
      • They are called using an object of the class.
    2. Static Methods:

      • Static methods belong to the class itself, not to individual instances.
      • They can only access static members (variables and methods) of the class.
      • Static methods are called using the class name, not an object.
    3. Constructor:

      • A special type of method that is used to initialize an object when it is created. It has the same name as the class and does not return a value.
    4. Destructor:

      • A special type of method that is automatically called when an object is destroyed. It is used for cleanup operations, like deallocating memory.
    5. Accessors and Mutators (Getters and Setters):

      • Getters are methods used to retrieve the value of an attribute.
      • Setters are methods used to modify the value of an attribute.

    Basic Syntax of Methods in C++

    The general syntax for defining methods within a class in C++ is:

    class ClassName {
    public:
        // Method declaration
        returnType methodName(parameters) {
            // Method body
            // operations on class data (attributes)
        }
    };
    
    • returnType: The type of data the method returns (e.g., int, double, void).
    • methodName: The name of the method.
    • parameters: The inputs (arguments) passed to the method, if any.

    Example of a Simple Method in C++

    #include <iostream>
    using namespace std;
    
    class Calculator {
    public:
        // Instance method to add two numbers
        int add(int a, int b) {
            return a + b;
        }
    
        // Instance method to subtract two numbers
        int subtract(int a, int b) {
            return a - b;
        }
    
        // Instance method to multiply two numbers
        int multiply(int a, int b) {
            return a * b;
        }
    
        // Instance method to divide two numbers
        double divide(int a, int b) {
            if (b != 0)
                return (double)a / b;
            else {
                cout << "Error: Division by zero!" << endl;
                return 0;
            }
        }
    };
    
    int main() {
        Calculator calc;
        int x = 10, y = 5;
    
        cout << "Sum: " << calc.add(x, y) << endl;
        cout << "Difference: " << calc.subtract(x, y) << endl;
        cout << "Product: " << calc.multiply(x, y) << endl;
        cout << "Quotient: " << calc.divide(x, y) << endl;
    
        return 0;
    }
    

    Explanation of the Code:

    • The Calculator class contains instance methods (add(), subtract(), multiply(), and divide()) that perform basic arithmetic operations.
    • These methods take two parameters (a and b) and return the result of the operation.
    • The main() function creates an object calc of the Calculator class and calls its methods to perform calculations.

    Instance Methods

    Instance methods are the most common type of method in OOP. These methods operate on the instance data (attributes) of the object and can be used to manipulate or return the object's internal state.

    • They are defined inside the class and are called using an object of that class.

    Example (C++):

    class Rectangle {
    private:
        int length;
        int width;
    
    public:
        // Constructor to initialize the rectangle
        Rectangle(int l, int w) : length(l), width(w) {}
    
        // Instance method to calculate area
        int getArea() {
            return length * width;
        }
    
        // Instance method to set length
        void setLength(int l) {
            length = l;
        }
    
        // Instance method to set width
        void setWidth(int w) {
            width = w;
        }
    };
    
    int main() {
        Rectangle rect(10, 5);
        cout << "Area: " << rect.getArea() << endl;
    
        rect.setLength(15);  // Change length using setter method
        rect.setWidth(10);   // Change width using setter method
        cout << "Updated Area: " << rect.getArea() << endl;
    
        return 0;
    }
    

    Explanation of Instance Methods:

    • The getArea() method is an instance method that calculates and returns the area of the rectangle by accessing the object's length and width attributes.
    • The setLength() and setWidth() methods are mutators (setters) that allow modifying the object's internal state.
    • The main() function creates a Rectangle object rect and uses instance methods to interact with the object.

    Static Methods

    A static method belongs to the class itself, not to any particular instance. Static methods can be called using the class name, without creating an object. They can only access static members of the class (i.e., variables or methods marked as static).

    • Static methods are often used for utility functions or operations that do not depend on the instance-specific data.

    Example (Static Methods in C++):

    class MathUtility {
    public:
        // Static method to calculate the square of a number
        static int square(int num) {
            return num * num;
        }
    
        // Static method to calculate the cube of a number
        static int cube(int num) {
            return num * num * num;
        }
    };
    
    int main() {
        // Calling static methods using class name
        cout << "Square of 5: " << MathUtility::square(5) << endl;
        cout << "Cube of 5: " << MathUtility::cube(5) << endl;
    
        return 0;
    }
    

    Explanation of Static Methods:

    • The square() and cube() methods are static methods, meaning they belong to the class MathUtility itself, not to individual objects.
    • They are called using the class name (MathUtility::square()), not an object of the class.
    • Static methods cannot directly access instance data but can access static variables and other static methods.

    Constructors and Destructors as Methods

    Constructor:

    • A constructor is a special method used to initialize an object when it is created. Constructors have the same name as the class and do not return any value.
    • They are typically used to assign initial values to the object’s attributes.

    Example of Constructor:

    class Car {
    private:
        string model;
        int year;
    
    public:
        // Constructor to initialize the car object
        Car(string m, int y) : model(m), year(y) {}
    
        void displayInfo() {
            cout << "Model: " << model << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1("Toyota", 2022);  // Constructor called during object creation
        car1.displayInfo();
        return 0;
    }
    

    Destructor:

    • A destructor is a special method called when an object is destroyed. It is used for cleanup, such as releasing memory or closing files.
    • Destructors have the same name as the class, prefixed with a tilde (~), and do not return a value or take parameters.

    Example of Destructor:

    class Car {
    private:
        string model;
    
    public:
        // Constructor
        Car(string m) : model(m) {
            cout << "Car created: " << model << endl;
        }
    
        // Destructor
        ~Car() {
            cout << "Car destroyed: " << model << endl;
        }
    };
    
    int main() {
        Car car1("Honda");  // Constructor is called here
        // Destructor will be called automatically when car1 goes out of scope
        return 0;
    }
    

    Accessors and Mutators (Getters and Setters)

    • Accessors (also known as getters) are methods used to retrieve the value of an object's attribute.
    • Mutators (also known as setters) are methods used to modify the value of an object's attribute.

    Example:

    class Student {
    private:
        string name;
        int age;
    
    public:
        // Getter method (accessor)
        string getName() {
            return name;
        }
    
        // Setter method (mutator)
        void setName(string n) {
            name = n;
        }
    
        // Getter method (accessor)
        int getAge() {
            return age;
        }
    
        // Setter method (mutator)
        void setAge(int a) {
            age = a;
        }
    };
    
    int main() {
        Student s;
        s.setName("John");
        s.setAge(20);
    
        cout << "Name: " <<
    
    Previous topic 5
    Classes
    Next topic 7
    Objects and 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 time8 min
      Word count1,394
      Code examples0
      DifficultyIntermediate