- 2072 Kartik · 6 marks
Concept of class with example
Short answer
A class is a user-defined type that bundles data members and member functions into a single unit. For example, class Student has private roll and marks, public getData() and display(); objects s1 and s2 each hold their own data, accessed only through public methods.
With a suitable example, explain the concept of class in C++.
A class is a user-defined data type that groups data members (attributes) and member functions (behaviour) into a single unit. It is a blueprint; no memory is allocated for it until objects are created. Members can be private, protected or public; by default members of a class are private.
General form
class ClassName {
private:
// data members (hidden)
public:
// member functions (interface)
}; // semicolon is required
Example
#include <iostream>
using namespace std;
class Student {
private:
int roll;
float marks;
public:
void getData(int r, float m); // declaration
void display() { // defined inside the class (inline)
cout << "Roll: " << roll << ", Marks: " << marks << endl;
}
};
void Student::getData(int r, float m) { // defined outside using ::
roll = r;
marks = m;
}
int main() {
Student s1, s2; // objects
s1.getData(1, 78.5);
s2.getData(2, 85);
s1.display();
s2.display();
return 0;
}
Output
Roll: 1, Marks: 78.5
Roll: 2, Marks: 85
Points:
- Each object has its own copy of the data members; member functions are shared by all objects.
- Private members are reached only through public functions (data hiding).
- A member function can be defined inside the class, or outside using the scope resolution operator
::. - Objects are accessed with the dot operator (
s1.display()).
✓ Answer checked by Claude Opus 5.5 (high effort)