- A
classbundles data (members) and functions (methods). public,private(the default in a class) andprotectedcontrol access.- A constructor has the class name; use a member initialiser list to set members.
- A destructor
~ClassName()runs when the object is destroyed. - Mark methods that do not modify the object as
const.
C++ Classes & Objects
Members, constructors and access specifiers.
✍️ 2 exercises in this lessonKey Takeaways: C++ Classes & Objects
Mastering C++ Classes & Objects helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C++ Classes & Objects Code Example
C++#include <iostream>
#include <string>
class Account {
public:
Account(std::string owner, double balance = 0)
: owner_(std::move(owner)), balance_(balance) {}
void deposit(double amount) { balance_ += amount; }
double balance() const { return balance_; }
const std::string& owner() const { return owner_; }
private:
std::string owner_;
double balance_;
};
int main() {
Account acc("Hina", 1000);
acc.deposit(500);
std::cout << acc.owner() << ": " << acc.balance() << "\n";
return 0;
}
Output
Hina: 1500
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
C++ Classes & Objects Practice Exercises
Check what you learned in “C++ Classes & Objects”.
/ 2 solved
Fill in the blank
Mark a method that does not modify the object.
double balance() { return balance_; }
✓ Correct!
Not quite. Try again.
Multiple choice
What is the default access in a C++ class?
✓ Correct!
Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services