0
0
C++programming~5 mins

Class definition syntax in C++

Choose your learning style9 modes available
Introduction

A class lets you group data and actions together like a blueprint for objects.

When you want to model real-world things like a car or a person in your program.
When you need to keep related data and functions organized together.
When you want to create many similar objects with the same structure.
When you want to hide details and only show what is needed to use the object.
Syntax
C++
class ClassName {
public:
    // data members (variables)
    // member functions (methods)
};

The class name should start with a capital letter by convention.

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

Examples
A simple class named Car with a speed variable and a drive function.
C++
class Car {
public:
    int speed;
    void drive() {
        // code to drive
    }
};
Class Person has name and age data, and a greet function to say hello.
C++
class Person {
public:
    std::string name;
    int age;

    void greet() {
        std::cout << "Hello, " << name << "!" << std::endl;
    }
};
Sample Program

This program defines a Dog class with name and age. It creates a Dog object, sets its name and age, then calls bark to print a message.

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();
    return 0;
}
OutputSuccess
Important Notes

Remember to end the class definition with a semicolon ;.

By default, class members are private. Use public: to make them accessible.

Summary

A class groups data and functions into one blueprint.

Use class ClassName { ... }; to define a class.

Public members can be accessed from outside the class.