Defining classes
- C++ course
- Intermediate
- Lesson 1/116
- 5 min
Learn to define classes with the class keyword.
Defining a class
A class is a template used to create objects. In C++ a class starts with the class keyword, followed by a name and a body in curly braces. A semicolon is required after the body.
Example: class Book { };. Here Book is the class name; the body is empty for now. Class names use PascalCase: UserAccount, ShoppingCart. Defining a class does not run it; it only prepares the template. To use the template you declare a variable to create an instance.
Creating instances
To create an object from a class you declare a variable. The simplest way in C++ is stack allocation: Book book;. This line allocates a Book object in memory and binds the book variable to it.
You can also give an initial value with braces: Book book{ };. You access the instance's members later with a dot: book.title. Here book is the object itself, not a reference.
Practice Define the Book class and create an instance
Define a Book class with an empty body. Inside main create an instance with Book book; and print "Book created" with std::cout.
Starter code
#include <iostream>
// Define the Book class here
int main() {
// Create a Book instance and print a message
return 0;
}Sample solution
#include <iostream>
class Book {
};
int main() {
Book book;
std::cout << "Book created";
return 0;
}Expected output
Book created
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid class definition?
- Book class { }
- function Book() { }
- class Book()
- class Book { }; Correct answer
Explanation: The class keyword comes first, then the name, braces and a semicolon.
2 Complete the class definition
____ Book { };
class Book { };
Explanation: The class keyword starts a class definition.
3 Match each keyword to its meaning
| Term | Meaning |
|---|---|
class |
Class template |
new |
Instance on the heap |
void |
No return value |
public |
Access from anywhere |