Q.1 Solution....

Q.1 Explain concepts of Class and Objects.

Answer :- 

Class and Objects in C++

Object-Oriented Programming (OOP) is one of the most powerful programming paradigms, and C++ is widely known as the first major programming language that fully supported OOP.
Two of its most fundamental concepts are Class and Object.

1. Class in C++

  • A class is a user-defined data type in C++ that acts as a blueprint for creating objects.

  • It bundles data members (variables) and member functions (methods) into a single unit.

  • Classes help achieve Encapsulation (data hiding) and Abstraction (showing only essential details).

Syntax of a Class:


class ClassName {
    // Access specifiers:
    // private, public, protected

private:
    // data members (variables)
    int a;

public:
    // member functions (methods)
    void setData(int x) {
        a = x;
    }

    void display() {
        cout << "Value of a: " << a << endl;
    }
};
  • Access Specifiers:

    • private: Members accessible only inside the class (default).

    • public: Members accessible from outside the class.

    • protected: Used mainly in inheritance.

2. Object in C++

  • An object is an instance of a class.

  • It represents a real-world entity (like Student, Car, BankAccount, etc.).

  • Using objects, we can access the data members and methods of a class.

Creating Objects:

3. Example Program


#include <iostream>
using namespace std;

// Define a class
class Student {
private:
    int rollNo;
    string name;
    float marks;

public:
    // Function to set data
    void setData(int r, string n, float m) {
        rollNo = r;
        name = n;
        marks = m;
    }

    // Function to display data
    void displayData() {
        cout << "Roll No: " << rollNo << endl;
        cout << "Name: " << name << endl;
        cout << "Marks: " << marks << endl;
    }
};

int main() {
    // Create objects of Student class
    Student s1, s2;

    // Set data for students
    s1.setData(101, "Hardik", 89.5);
    s2.setData(102, "Rahul", 92.0);

    // Display data
    cout << "Student 1 Details:" << endl;
    s1.displayData();

    cout << "\nStudent 2 Details:" << endl;
    s2.displayData();

    return 0;
}

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *