Menu
Coddy logo textTech

Introduction to OOP in C++

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 5 of 104.

Object-Oriented Programming organizes code into classes that bundle data and behavior together.

A simple class with public members

class Dog {
public:
    std::string name;
    int age;
    
    std::string bark() {
        return name + " says Woof!";
    }
};

Creating and using an object

Dog dog;
dog.name = "Buddy";
dog.age = 3;

std::cout << dog.bark() << std::endl;

Output:

Buddy says Woof!

A class defines the structure — what data it holds and what actions it can perform. An object is a specific instance you create and use. Members under public: can be accessed from anywhere.

challenge icon

Challenge

Easy

Create a Dog class with public members and methods:

  • Public members: name (string) and age (int)
  • bark() — returns "<name> says Woof!"
  • info() — returns "<name> is <age> years old"

Cheat sheet

Object-Oriented Programming organizes code into classes that bundle data and behavior together.

A class defines the structure — what data it holds and what actions it can perform. An object is a specific instance you create and use.

Defining a class with public members:

class Dog {
public:
    std::string name;
    int age;
    
    std::string bark() {
        return name + " says Woof!";
    }
};

Creating and using an object:

Dog dog;
dog.name = "Buddy";
dog.age = 3;

std::cout << dog.bark() << std::endl;
// Output: Buddy says Woof!

Members under public: can be accessed from anywhere.

Try it yourself

#include <iostream>
#include "Dog.h"

int main() {
    std::string name;
    int age;
    std::getline(std::cin, name);
    std::cin >> age;
    
    Dog dog;
    dog.name = name;
    dog.age = age;
    
    std::cout << dog.bark() << std::endl;
    std::cout << dog.info() << std::endl;
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming