Classes and constructors
Until now you stored data in loose variables and processed it with functions. A class joins both: it groups the data (members) and the operations that handle them (methods) into a single new type. That way you can create objects like Account, Product or Point and work with them as if they were language types. In C++ the difference between class and struct is minimal: in class everything is private by default and in struct everything is public. By convention, struct is used for simple data and class when there are rules to protect.
Defining a class
A class is declared with class Name { ... };, without forgetting the final semicolon. Inside, public: marks what anyone can use and private: what only the class's methods see. Methods that do not modify the object are marked const at the end of the signature: double balance() const;. This is not decoration: it allows calling them on constant objects and the compiler prevents them from modifying members by mistake. Data members are usually private and carry a suffix or prefix (here we use a trailing underscore, balance_) to tell them apart from parameters.
Constructors and the initializer list
A constructor is a special method with the same name as the class and no return type; it runs automatically when the object is created and leaves the object in a valid state. The recommended way to initialize members is the initializer list, placed between the colon and the body: Account(std::string owner, double initial) : owner_{std::move(owner)}, balance_{initial} {}. Members are initialized in the order they are declared in the class, not in the order of the list, so keep both the same. If you write no constructor, the compiler generates a default one, but as soon as you write one, that one is no longer generated.
#include <iostream>
#include <string>
#include <utility>
class Account {
public:
Account(std::string owner, double initial)
: owner_{std::move(owner)}, balance_{initial} {}
// delegating constructor: an account that starts empty
explicit Account(std::string owner) : Account{std::move(owner), 0.0} {}
void deposit(double amount) {
if (amount > 0) {
balance_ += amount;
}
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) {
return false; // rejected: invalid amount or not enough money
}
balance_ -= amount;
return true;
}
double balance() const { return balance_; }
const std::string& owner() const { return owner_; }
private:
std::string owner_;
double balance_;
};
int main() {
Account a{"Ana", 100.0};
a.deposit(50.0);
bool ok = a.withdraw(500.0);
std::cout << a.owner() << ": " << a.balance() << " ok=" << ok << '\n';
// Ana: 150 ok=0
Account b{"Luis"};
std::cout << b.owner() << ": " << b.balance() << '\n'; // Luis: 0
return 0;
}Notice three decisions. First, the members are private: nobody can leave the balance in an invalid value from outside, only through deposit and withdraw, which validate. Second, the one-parameter constructor delegates to the other and is marked explicit to prevent implicit conversions from std::string to Account, a source of subtle bugs. Third, the reading methods are const and return the string by const reference to avoid copying it. The classic beginner mistake is forgetting the semicolon after the closing brace of the class, which produces confusing error messages several lines further down.
Default member initializers
Since C++11 you can give an initial value directly in the member declaration: int count_{0};. It is useful when several constructors share the same default value, and it avoids the mistake of leaving a member uninitialized, whose value would be unpredictable garbage. If you want the compiler to generate the default constructor even though you have others, write Account() = default;. With these pieces you can already model almost any simple entity: decide what data it has, what its rules are, and expose only the necessary methods.
#include <iostream>
struct Counter {
int value_{0}; // default member initializer
int step_{1};
Counter() = default; // keeps the generated default constructor
explicit Counter(int step) : step_{step} {} // value_ still starts at 0
void tick() { value_ += step_; }
};
int main() {
Counter a;
Counter b{5};
a.tick();
b.tick();
b.tick();
std::cout << a.value_ << ' ' << b.value_ << '\n'; // 1 10
return 0;
}✎ मेरे नोट्स
केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर