A class is a user-defined type.
- C.2: Use
class
if the class has an invariant; usestruct
if the data members can vary independently - C.7: Don't define a class or enum and declare a variable of its type in the same statement
- C.ctor: Constructors
- C.hier: Class hierarchies (OOP)
- C.121: If a base class is used as an interface, make it a pure abstract class
- C.hierclass: Designing classes in a hierarchy
- C.hier-access: Accessing objects in a hierarchy
struct Pair{
// by default public
string name;
int volume;
};
class Date{
public:
Date(int yy, Mont mm, char dd);
// ..
private:
int y;
Month m;
char d;
};
C.8: Use class rather than struct if any member is non-public
struct Data{};
Data data{}; // do
struct Data{} data{}; // do not
class Date{
Date(int dd, int mm, int yy) : d{dd}, m{mm}, y{yy}{
if ( !is_valid(d, m, y) ) throw Bad_date(); // enforce invariant
}
private:
int d, m, y;
};
class My_interface{
public:
// ... only pure virtual functions (virtual f() = 0) ...
virtual ~My_interface(){} // or = default
};
virtual
: this is a new virtual functionoverride
: this is a non-final overrider (it matches its base clase)final
: this is a final overrider (it can't be overridden)
void use(int i){
auto p = new int {7}; // bad: initialize local pointers with new
auto q = make_unique<int>{9}; // ok: guarantee the release of the memory-allocated for 9
if (0 < i) return; // maybe return and leak
delete p; // to late
}
auto q = make_unique<Foo>(7); // do
unique_ptr<Foo> p { new Foo{7} }; // do not
void test(){
auto q = make_shared<Bar>(7); // do
shared_ptr<Bar> p { new Bar{7} }; // do not
}