Classes
Programming Languages · C++ Going Further · 14 min
Design your own types with fields, methods and constructors, and make objects from them.
Your own type
A class is a blueprint for your own type. It bundles related variables, called fields. public: lets code outside the class use them. Each thing you make from a class is an object:
class Dog {
public:
std::string name;
int age;
};
Dog d;
d.name = "Rex";
Don't forget the ; after the class's closing brace!
Above
main, write a classBookwith public fieldsstd::string titleandint pages.In
main, make aBook b, set itstitleto"Dune"and itspagesto412.Print
Dune has 412 pagesusingb.titleandb.pages.
Methods: functions inside a class
A method is a function that lives inside a class. It can use the object's fields directly. Call it with a dot:
class Dog {
public:
std::string name;
void bark() {
std::cout << name << " says woof\n";
}
};
d.bark();
Inside
Book, add a methodvoid describe()that prints the title,:, the pages andpages.In
main, callb.describe().
Constructors
A constructor is a special method that runs when an object is made. It has the class's name and no return type. Use it to fill in the fields in one go:
class Dog {
public:
std::string name;
Dog(std::string n) {
name = n;
}
};
Dog d("Rex");
Add a constructor
Book(std::string t, int p)that setstitleandpages.In
main, createBook b("Dune", 412);and callb.describe().
Many objects, one class
One class can make as many objects as you like. Each object keeps its own fields, so changing one book never touches another. That's the whole point of a blueprint.
Create a second
Bookcalledhfor"The Hobbit"with310pages.Call
describe()onhtoo.
Put it together: bank account
Finish a tiny BankAccount class. It already has an owner, a balance and a constructor. Give it two methods, then try it out.
Add a method
void deposit(int amount)that addsamounttobalance.Add a method
void show()that prints the owner,:, then the balance.In
main, make an account for"Ada"with100, deposit50, then callshow().
More in C++ Going Further
Previous: References & Pointers · Next: Inheritance and Polymorphism