22 Classes-and-Objects-in-CPP
22 Classes-and-Objects-in-CPP
Topperworld.in
• A Class is a user-defined data type that has data members and member
functions.
• Data members are the data variables and member functions are the
functions used to manipulate these variables together, these data
members and member functions define the properties and behavior of
the objects in a Class.
An Object is an instance of a Class. When a class is defined, no memory
is allocated but when it is instantiated (i.e. an object is created)
memory is allocated.
©Topperworld
C++ Programming
➢ A class is defined in C++ using the keyword class followed by the name
of the class.
➢ The body of the class is defined inside the curly brackets and terminated
by a semicolon at the end.
❖ Declaring Objects
When a class is defined, only the specification for the object is defined; no
memory or storage is allocated. To use the data and access functions defined
in the class, you need to create objects.
Syntax:
ClassName ObjectName;
#include <iostream>
class Student {
public:
// Data members
std::string name;
int age;
©Topperworld
C++ Programming
// Constructor
Student(std::string n, int a) {
name = n;
age = a;
}
// Member function to display student information
void displayInfo() {
std::cout << "Name: " << name << "\n";
std::cout << "Age: " << age << "\n";
}
};
int main() {
// Creating an object of the Student class
Student student1("Alice", 20);
©Topperworld
C++ Programming
Output:
Using object:
Name: Alice
Age: 20
Using member function:
Name: Alice
Age: 20
int main() {
MyClass obj;
obj.insideFunction();
outsideFunction(obj);
return 0;
Output:
Inside class function.
Outside class function.
©Topperworld