CLASS AND OBJECTS IN C++
1. Introduction to Class and Object
-----------------------------------
- A class is a user-defined data type that holds data members and member functions.
- An object is an instance of a class.
Syntax:
class ClassName {
// data members
// member functions
};
2. Specifying a Class
----------------------
Example:
class Student {
int rollNo;
string name;
public:
void getData();
void showData();
};
3. Access Specifiers
---------------------
- public: Members are accessible from outside the class.
- private: Members are accessible only within the class (default access specifier).
- protected: Members are accessible in the class and its derived classes.
Example:
class Demo {
private:
int a;
public:
void display();
};
4. Defining Member Functions
-----------------------------
a) Inside the Class:
class Sample {
public:
void show() {
cout << "Inside class function." << endl;
};
b) Outside the Class:
class Sample {
public:
void show();
};
void Sample::show() {
cout << "Outside class function." << endl;
5. Creating Objects
--------------------
Example:
class Student {
public:
void display() {
cout << "Student object!" << endl;
};
int main() {
Student s1; // Object created
s1.display();
return 0;
6. Memory Allocation for Objects
--------------------------------
- Memory for member variables is allocated when an object is created.
- Each object has its own copy of data members.
- Member functions are shared and not separately allocated for each object.
Example:
class Example {
int x, y;
public:
void setData(int a, int b) {
x = a;
y = b;
};
int main() {
Example e1, e2; // Separate memory for x and y in each object
e1.setData(1, 2);
e2.setData(3, 4);
return 0;
Summary:
--------
- Class = Blueprint, Object = Instance
- Access specifiers control visibility
- Functions can be defined inside or outside class
- Memory is allocated only when objects are created