Introduction to Class and Object, Declaring Members and Methods in a class, declaring objects in c++

 Introduction to Class and Object

 

Class

·       User-defined data typeà binds data (variables) and functions (methods) together.

·       Class = blueprint / template

·       Not occupy memory until objects are created.

Example in real world:

  • Class: Car
  • Data members: color, model, fuel
  • Member functions: start(), stop(), accelerate()

 

Syntax

class ClassName {

public:

    // Data Members (variables)

    // Member Functions (methods)

};

 

Example: Simple Class

#include <iostream>

using namespace std;

 

class Student {

public:

    string name;

    int age;

 

    void display() {

        cout << "Name: " << name << endl;

        cout << "Age: " << age << endl;

    }

};

 

int main() {

    Student s1;     // creating object

    s1.name = "Pankaj";

    s1.age = 20;

    s1.display();

    return 0;

}

 

OUTPUT

Name: Pankaj

Age: 20


  

KEY TERMS IN CLASS

1. Data Members

Variables inside a class. Example: name, age

 

2. Member Functions

Functions inside the class. Example: display()

 

3. Access Specifiers

Define the access level of members:

Specifier

Meaning

public

Accessible everywhere

private

Accessible only inside class (default)

protected

For inheritance

 

Example:

class A {

private:

    int x;

public:

    void setX(int val) { x = val; }

};

 =======================================================

 

OBJECT

An instance of a class.
created from the class and occupies memory.

Object = data + methods

 

Example:

Car myCar;   // myCar is an object

 

CREATING OBJECTS

Multiple ways:

 

Method 1:

Student s1;

 

Method 2:

Student s1, s2, s3;

 

Method 3 (Dynamic object):

Student *p = new Student();

p->age = 20;


 

ACCESSING CLASS MEMBERS

Using the dot operator (.) for normal objects:

s1.age = 21;

s1.display();

 

Using arrow operator (->) for pointers:

p->display();


 

MEMORY ALLOCATION

  • Class → No memory
  • Object → Takes memory for data members only

Example:

Student s1;

Memory allocated for:

  • string name
  • int age

 

FEATURES OF CLASS & OBJECT

 Encapsulation

Combines data + functions

Reusability

One class, multiple objects

Abstraction

Hides internal implementation


EXAMPLE 2: Class with Private Members

#include <iostream>

using namespace std;

 

class Bank {

private:

    int balance;

 

public:

    void setBalance(int b) {

        balance = b;

    }

 

    void showBalance() {

        cout << "Balance = " << balance;

    }

};

 

int main() {

    Bank b1;

 

    b1.setBalance(5000);

    b1.showBalance();

 

    return 0;

}


 EXAMPLE 3: Multiple Objects

class Car {

public:

    string brand;

    int speed;

 

    void show() {

        cout << brand << " runs at " << speed << " km/h\n";

    }

};

 

int main() {

    Car c1, c2;

 

    c1.brand = "Honda";

    c1.speed = 120;

 

    c2.brand = "BMW";

    c2.speed = 200;

 

    c1.show();

    c2.show();

}


 

ADVANTAGES OF USING CLASSES & OBJECTS

1. Modularity

Break the program into smaller modules.

2. Code Reusability

Define once, use many times.

3. Data Security

Using private, protected.

4. Real-World Modeling

Car, Student, Bank account → good examples.

========================================================================= 

Declaring Members and Methods in a Class

 

Basic Syntax of Class

class ClassName {

private:

    // data members

    // member functions

 

public:

    // data members

    // member functions

 

protected:

    // data members

    // member functions

};

 

Declaring Member Functions

Member functions define the behavior of the class.

There are two ways to declare them:


 

A. Define inside the class

class Student {

public:

    string name;

    int roll;

 

    void display() {          // method defined inside class

        cout << "Name: " << name << endl;

        cout << "Roll: " << roll << endl;

    }

};

Automatically becomes an inline function
Suitable for small functions


 

B. Declare inside & Define outside the class

More readable for large programs.

Inside class → only declaration:

class Student {

public:

    string name;

    int roll;

 

    void display();   // declaration only

};

 

Outside class → full definition:

void Student::display() {

    cout << "Name: " << name << endl;

    cout << "Roll: " << roll << endl;

}

 

Use scope resolution operator::
Syntax:

ClassName::FunctionName()

==============================================================

 

Creating Objects & Accessing Members

 

Types of Members

(A) Data Members

  • int, float, string
  • arrays
  • objects of other classes

 

Example:

int age;

float salary;

string name;

(B) Member Functions

Types:

  1. Getters & Setters
  2. Utility functions
  3. Constructor & Destructor
  4. Static functions
  5. Inline functions
  6. Friend functions (special case)

Example:

void setData();

float calculateGrade();

 

  1. Getters & Setters

Getters (Accessors):

  • functions designed to retrieve the values of private or protected data members.

 

Setters (Mutators):

  • Functions designed to modify the values of private or protected data members.
  • Take a parameter representing the new value to be assigned to the data member.

 

Example: C++

#include <iostream>
#include <string>

class Person {
private:
    std::string name;
    int age;

public:
    // Setter for name
    void setName(const std::string& newName) {
        name = newName;
    }

    // Getter for name
    std::string getName() const {
        return name;
    }

    // Setter for age with validation
    void setAge(int newAge) {
        if (newAge >= 0) {
            age = newAge;
        } else {
            std::cout << "Age cannot be negative!" << std::endl;
        }
    }

    // Getter for age
    int getAge() const {
        return age;
    }
};

int main() {
    Person p;
    p.setName("Alice");
    p.setAge(30);

    std::cout << "Name: " << p.getName() << std::endl;
    std::cout << "Age: " << p.getAge() << std::endl;

    p.setAge(-5); // This will trigger the validation message

    return 0;
}

 

Advantages of using Getters and Setters:

  • Data Encapsulation and Hiding: 
  • Data Validation: 
  • Flexibility and Maintainability: 
  • Readability: 

 

2.    Utility functions

Provide common, reusable functionalitiesà, simplifying tasks or performing operations.

They can be categorized into two main types:

  • Standard Library Utility Functions: 

These are predefined functions provided by the C++ Standard Library, accessible by including the appropriate header files. Examples include:

  • Mathematical functions: sqrt(), abs() etc.
  • Character manipulation functions: isdigit(), isalpha() etc.
  • String manipulation functions: getline(), stoi(), to_string() etc.
  • Memory management functions: malloc(), free() etc.
  • General utilities: exit(), abort() etc.

 

  • User-Defined Utility Functions: 

Written by the programmer to encapsulate specific, reusable logic within their own codebase. They are often created to:

  • Reduce code duplication: 
  • Improve code readability and organization: 
  • Enhance modularity: 
  • Handle specific domain-related tasks: 

 

Example of a User-Defined Utility Function: C++

#include <iostream>
#include <string>

// A utility function to check if a string is a palindrome
bool isPalindrome(const std::string& str) {
    std::string reversed_str = str;
    std::reverse(reversed_str.begin(), reversed_str.end());
    return str == reversed_str;
}

int main() {
    std::string word1 = "madam";
    std::string word2 = "hello";

    if (isPalindrome(word1)) {
        std::cout << word1 << " is a palindrome." << std::endl;
    } else {
        std::cout << word1 << " is not a palindrome." << std::endl;
    }

    if (isPalindrome(word2)) {
        std::cout << word2 << " is a palindrome." << std::endl;
    } else {
        std::cout << word2 << " is not a palindrome." << std::endl;
    }

    return 0;
}

 

 


Access Specifiers

Control the visibility of class members.

Specifier

Access

Used For

public

Accessible from anywhere

Interface / APIs

private

Accessible only inside the class

Data hiding

protected

Accessible in derived classes

OOP inheritance


 

Example Program

#include <iostream>

using namespace std;

 

class Rectangle {

private:

    int length;      // private data member

    int width;

 

public:

    void setData(int l, int w) {      // member function

        length = l;

        width = w;

    }

 

    int area() {                      // member function

        return length * width;

    }

};

 

int main() {

    Rectangle r1;           // object created

    r1.setData(10, 5);      // calling method

 

    cout << "Area = " << r1.area();

    return 0;

}


 

Advantages of declaring members inside a class

  1. Encapsulation
  2. Data hiding
  3. Reusability
  4. Organized structure
  5. Security & abstraction

 

Declare Objects of a Class

 There are 5 common ways:


Method 1: Declare an object like a normal variable

ClassName objectName;

Example:

Car c1;        // c1 is an object of the Car class


Method 2: Declare multiple objects together

Car c1, c2, c3;


Method 3: Declare an object using a pointer

Car *ptr = new Car();

ptr->speed = 100;

  • ptr-> is used instead of .
  • This allocates memory on heap.

Method 4: Declare objects inside another class

Used in OOP concepts like composition/nesting.

class Engine {};

 

class Car {

    Engine e;      // 'e' is an object of Engine inside Car

};


Method 5: Create an object using constructors

Car c1();     // calls default constructor

Car c2(100);  // calls parameterized constructor


 

 Memory Allocation of Objects

When declaring an object:

Car c;

  • Object stored on the stack
  • Automatically destroyed at the end of the scope

Car *p = new Car;

  • Object stored on the heap
  • Must use delete p; manually

Example:

#include <iostream>

using namespace std;

 

class Student {

public:

    string name;

    int marks;

 

    void display() {

        cout << "Name: " << name << ", Marks: " << marks << endl;

    }

};

 

int main() {

    // Method 1

    Student s1;

    s1.name = "Rahul";

    s1.marks = 90;

    s1.display();

 

    // Method 2

    Student s2, s3;

 

    // Method 3

    Student *s4 = new Student();

    s4->name = "Pankaj";

    s4->marks = 85;

    s4->display();

    delete s4;

 

    return 0;

}


 

Object Declaration Inside a Class (Nesting)

class Address {

public:

    string city;

};

 

class Person {

public:

    Address addr;   // Object of Address

};

This is called "Object Composition".


 

Declaring Objects Outside Class Using Scope Resolution

class Demo {

public:

    void show();

};

 

void Demo::show() {

    cout << "Hello!";

}

 

int main() {

    Demo d;    // object declared in main

    d.show();

}

=======================================================================

Post a Comment

0 Comments