0
0
C++programming~5 mins

Creating objects in C++

Choose your learning style9 modes available
Introduction

Objects let us make real things in code that have properties and actions. Creating objects helps us organize and use data easily.

When you want to represent a real-world thing like a car or a person in your program.
When you need to group related data and functions together.
When you want to create multiple similar items with their own values.
When you want to use features of object-oriented programming like reuse and organization.
Syntax
C++
ClassName objectName;  // creates an object of ClassName

// Or with constructor
ClassName objectName(constructor_arguments);

You must define a class before creating objects of it.

Objects are created using the class name followed by the object name.

Examples
This creates a simple object myCar from class Car.
C++
class Car {
public:
    int speed;
};

Car myCar;  // creates an object named myCar of type Car
This creates an object with a constructor that sets the speed.
C++
class Car {
public:
    int speed;
    Car(int s) { speed = s; }
};

Car myCar(100);  // creates myCar with speed 100
Sample Program

This program creates a Dog object named myDog with a name and age. It then prints the dog's details and makes it bark.

C++
#include <iostream>
#include <string>
using namespace std;

class Dog {
public:
    string name;
    int age;

    Dog(string n, int a) {
        name = n;
        age = a;
    }

    void bark() {
        cout << name << " says Woof!" << endl;
    }
};

int main() {
    Dog myDog("Buddy", 3);  // create object myDog
    cout << "My dog's name is " << myDog.name << "." << endl;
    cout << "He is " << myDog.age << " years old." << endl;
    myDog.bark();
    return 0;
}
OutputSuccess
Important Notes

Objects store their own data separately from other objects.

Constructors help set initial values when creating objects.

Use dot . to access object properties and methods.

Summary

Objects are created from classes to represent things in code.

Use the class name followed by the object name to create an object.

Constructors can set up objects with starting values.