0
0
C++programming~5 mins

Real-world modeling in C++

Choose your learning style9 modes available
Introduction

Real-world modeling helps us turn things we see around us into code. It makes programs easier to understand and work with.

When you want to represent a person with their name and age in a program.
When you need to model a car with its color, brand, and speed.
When creating a game character with health, position, and abilities.
When managing a library system with books, authors, and borrowers.
Syntax
C++
class ClassName {
public:
    // attributes (data members)
    Type attribute1;
    Type attribute2;

    // methods (functions)
    void methodName() {
        // code
    }
};
Use class to create a blueprint for real-world things.
Attributes store information, methods define actions.
Examples
This class models a person with a name and age.
C++
#include <string>
using namespace std;

class Person {
public:
    string name;
    int age;
};
This class models a car with brand, color, speed, and a honk action.
C++
#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    string color;
    int speed;

    void honk() {
        cout << "Beep beep!" << endl;
    }
};
Sample Program

This program creates a Person named Alice who is 30 years old and then introduces her by printing a message.

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

class Person {
public:
    string name;
    int age;

    void introduce() {
        cout << "Hi, I am " << name << " and I am " << age << " years old." << endl;
    }
};

int main() {
    Person friend1;
    friend1.name = "Alice";
    friend1.age = 30;

    friend1.introduce();

    return 0;
}
OutputSuccess
Important Notes

Remember to use public: to allow access to attributes and methods from outside the class.

Classes help organize code by grouping related data and actions together.

Summary

Real-world modeling uses classes to represent things and their behaviors.

Attributes hold information, methods perform actions.

This makes programs clearer and easier to manage.