OOP: CLASSES AND OBJECTS
What is a Class?
A class is a user-defined type.
It describes what kind of data an object will store and what actions the object can perform.
Simple definition:
A class is a blueprint for creating objects.
Example Idea
Think about a Student.
A student object may have:
- name
- id
- marks
And it may perform actions:
- display details
- update marks
- check pass/fail
The class describes this structure.
Basic Class Example
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int marks;
public:
void setDetails(const std::string& studentName, int studentMarks) {
name = studentName;
marks = studentMarks;
}
void display() const {
std::cout << name << " scored " << marks << '\n';
}
};
int main() {
Student student;
student.setDetails("Mina", 85);
student.display();
}
What the Class Contains
| Part | Meaning |
|---|---|
| Data members | Variables inside the class |
| Member functions | Functions inside the class |
| Access specifiers | Rules controlling access, such as private and public |
Does a Class Definition Use Object Memory?
The class definition itself is a type description. It does not create a real student object.
Memory for non-static data members is needed when you create an object.
Student s1; // object created
Student s2; // another object created
Connection to OOP
A class is where OOP starts in C++.
It lets you group:
- state: data members
- behavior: member functions
Viva Answer
A class is a user-defined type or blueprint that defines the data members and member functions of its objects. The class itself describes the structure; objects are the actual instances created from it.
Quick Check
- What is a class?
- What are data members?
- What are member functions?
- Does writing a class definition create an object?