class Example {
// declaration of variables
// method prototypes
// can be declared in this file or a seperate cpp file
void DoThing(int);
};
Example::DoThing(int x) {
// ... implementation of the function
}
class Example {
public:
int var;
void do_something() {std::cout << "doing something" << std::endl;}
};
class Example {
private:
int var;
void do_something() {std::cout << "doing something" << std::endl;}
};
class Example {
int var;
void do_something() {std::cout << "doing something" << std::endl;}
};
| Scope Type | Accessible inside the class | Accessible outside the class directly |
|---|---|---|
| private | Yes | No |
| public | Yes | Yes |
class Example {
private: // private is also implied if you don't specify visibility
int a;
public:
int getA() { return a; }
};
default constructors initialize all data members to default values (default constructor is used if no custom constructor is given)class Example {
private:
int a;
// lots of important variables that live on the heap
public:
int getA() { return a; }
Example() = default;
Example(int a_local) {
a = a_local;
std::cout << "custom constructor" << std::endl;
/* allocating memory, etc. ... */
}
};
class Example {
private:
int a;
// lots of important variables from the heap
public:
int getA() { return a; }
// ... constructors
~Example() {/* lots of deletes */};
};
static keyword means something else outside of class definitions!class StaticExample {
private:
static int a;
public:
void modify_static_var() { a++; }
static int getA() { return a; }
};
// init in implementing class
int static_example::a = 0;
class Child: public Example {
// we get `a` and `getA()` from example
private:
int b;
public:
int getB() { return b; }
int getAplusB() { return getA() + b; } // we can't use `a` directly since it's private
};
| scope | internally | subclasses | externally |
|---|---|---|---|
| private | yes | no | no |
| protected | yes | yes | no |
| public | yes | yes | yes |
: Parent(args) before the opening braceclass Example {
public:
int a;
Example(int a2) { a = a2; }
};
class Child: public Example {
public:
int b;
Child(int a2, int b2) : Example(a2) {
b = b2;
}
};
child objects with all the properties of an example object
This means we can safely cast a child object to an example object
child c;
example& e = dynamic_cast<example&>(c);
But not the other way around
example e;
child& c = dynamic_cast<child&>(e);
example.cpp: In function ‘int main()’:
example.cpp:20:38: error: cannot dynamic_cast ‘e’ (of type ‘class Example’) to type
‘class child&’ (source type is not polymorphic)
child& c = dynamic_cast<child&>(e);
^
hardware_applications/inheritance folderinheritance.cpp is already completeRJRobotExtended class should have the following:
duration for an amount of time to drive on the edge of the square
std::chrono::milliseconds typeDriveEdge(): drive forward for duration millisecondsDriveCorner(): turn 90 degrees rightDriveInSquare(): drive in a square, calling your private