Skip to Content
Learn
Classes and Objects
Creating Objects

Now that you have a class, let’s create some objects! To refresh your memory, an object is an instance of a class, which encapsulates data and functionality pertaining to that data.

To create (or instantiate) an object, we can do this:

City accra;

We can give the object’s attributes values like this (note that these must be attributes you defined in the class):

accra.population = 2270000;

Later, we can access this information using the method we added to the City class (if it’s in a public part of the class):

accra.get_population();

Instructions

1.

Flip over to song.hpp and song.cpp to see how the class and its methods are set up.

Then, in music.cpp, instantiate a new song electric_relaxation in main().

2.

Use Song‘s built-in .add_title() method to add a title to electric_relaxation: "Electric Relaxation".

3.

Use .get_title() to retrieve electric_relaxations title and print it to the terminal.

Folder Icon

Take this course for free

Already have an account?