Start learning free

LESSON 279 OF 667 · FUNCTIONS & CLASSES

Member Functions in C++

Lesson

TL ; DR:

  • A member function (or method) is a function declared inside a class. It can read and write the object's data members.


  • Define member functions under public: so they can be called from outside:

    class Dog {
    public:
        string name;
        Dog(string name) { this->name = name; }
    
        void bark() {
            cout << "Woof! I am " << name << endl;
        }
    };
    

  • Call it on an object with the dot operator: dog.bark();



Full lesson:

So far you've added data to a class with member variables and a constructor. The other half of OOP is behavior — actions an object can perform. That's what member functions are for.


Your task

Add a bark() member function that prints "Woof! I am " followed by the dog's name.

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check