0
0
C++programming~5 mins

Classes and objects in C++

Choose your learning style9 modes available
Introduction

Classes help you group related data and actions together. Objects are real examples made from classes.

When you want to model real things like cars or books in your program.
When you need to keep data and functions that work on that data together.
When you want to create many similar items with their own details.
When you want to organize your code to be easier to understand and reuse.
Syntax
C++
class ClassName {
public:
    // data members (variables)
    // member functions (methods)
};

// Create an object
ClassName objectName;

Use public: to allow access to members from outside the class.

Objects are instances of classes and hold their own data.

Examples
This defines a class Car with two pieces of data: brand and year. Then it creates an object myCar.
C++
#include <string>
using namespace std;

class Car {
public:
    string brand;
    int year;
};

Car myCar;
This class Light has a function to turn it on. The object lamp uses that function.
C++
class Light {
public:
    bool isOn;
    void switchOn() {
        isOn = true;
    }
};

Light lamp;
lamp.switchOn();
Sample Program

This program creates a Dog class with a name and age. It has a function to bark. We make a dog named Buddy, tell it to bark, and print its age.

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

class Dog {
public:
    string name;
    int age;

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

int main() {
    Dog myDog;
    myDog.name = "Buddy";
    myDog.age = 3;
    myDog.bark();
    cout << "Age: " << myDog.age << endl;
    return 0;
}
OutputSuccess
Important Notes

Remember to use public: to make members accessible outside the class.

Each object has its own copy of the data members.

Functions inside classes are called methods and can use the object's data.

Summary

Classes group data and functions to model real things.

Objects are individual examples made from classes.

Use classes to organize and reuse your code better.