Dec 30, 2024
class DerivedClass : <list of base classes>
<list of base classes>
is a comma-separated list of base classes, each prefixed by an access level specifier: public
, protected
, or private
.private
for classespublic
for structsclass Derived : Base; // Same as class Derived : private Base
struct Derived : Base; // Same as struct Derived : public Base
class Derived : Base
defaults to privateclass Derived : protected Base
class Derived : public Base
class Person {};
class Father : public Person {};
class Mother : public Person {};
class Child : public Father, public Mother {};
HAS A
relationship.class WeightMixin {
float weight_;
public:
float get_weight() const { return this->weight_; }
void update_weight(const float weight) { this->weight_ = weight; }
};
class Base {
public:
Base() { std::cout << "Initialized Base" << std::endl; }
~Base() { std::cout << "Destroying Base" << std::endl; }
};
class Derived : public Base {
public:
Derived() { std::cout << "Initialized Derived" << std::endl; }
~Derived() { std::cout << "Destroying Derived" << std::endl; }
};
Animal
: Cat
and Dog
.class Animal {
protected:
std::string name;
public:
Animal(std::string _name) : name(_name) {}
void eat(std::string food) {
std::cout << name << " eats " << food << std::endl;
}
};
Garfield
the cat eats milk and is printed with weight.Milo
the dog eats steak and is printed with weight.