Codeloft
0 0 XP

Classes and objects

9 min 20 XP + 10 for no hints

A class is a blueprint that bundles data and behavior together. An object is one thing built from that blueprint, the way many houses can be built from one plan.

Variables inside a class are called members, and functions inside it are called methods. Put them after public: so code outside the class can use them.

Create an object like any variable, Dog rex;, then use a dot: rex.name = "Rex"; and rex.bark();. A class definition ends with a semicolon after its closing brace.

Example
class Dog {
public:
    std::string name;
    void bark() {
        std::cout << name << " says woof!" << std::endl;
    }
};

int main() {
    Dog rex;
    rex.name = "Rex";
    rex.bark();
    return 0;
}
Output
Rex says woof!
Forgetting the semicolon after a class's closing brace is one of the most common C++ errors.

Your tasks

0 of 4 done
  1. Define class Car
  2. Give it a public std::string model
  3. Add a honk() method that prints "Beep!"
  4. End the class with }; and create a Car in main that calls honk()

Quick check

What is an object?

car.cppChecked as you type
No problems found. Unclosed tags, missing semicolons and errors show up here in plain words.