Creating Objects
Creating an object from a class is called instantiation.
ClassName objectName;
Example:
Student student;
Object Creation Looks Like Variable Declaration
Built-in type:
int age;
User-defined class type:
Student student;
Both declare a variable. The second variable is an object.
Multiple Objects
#include <iostream>
#include <string>
class Student {
private:
std::string name;
public:
void setName(const std::string& studentName) {
name = studentName;
}
void display() const {
std::cout << name << '\n';
}
};
int main() {
Student first;
Student second;
first.setName("Mina");
second.setName("Riaz");
first.display();
second.display();
}
first and second are separate objects.
Stack Objects
Most beginner objects are created like this:
Student student;
This object is destroyed automatically when its scope ends.
Dynamic Objects
You can create objects dynamically:
Student* student = new Student();
delete student;
This teaches the basic mechanism, but modern C++ usually prefers smart pointers:
#include <memory>
auto student = std::make_unique<Student>();
You will study ownership more deeply later.
Connection to Constructors
When an object is created, its constructor is called.
For now, remember:
Student student; // creates object and calls constructor
Constructors are covered in Chapter 4.
Viva Answer
Creating an object from a class is called instantiation. Objects can be created like normal variables, and each object gets its own non-static data. When an object is created, its constructor is called.
Quick Check
- What is instantiation?
- Are
firstandsecondthe same object? - When is a stack object destroyed?
- What happens when an object is created?