foo my_foo;or
foo my_foo(); // a recent change allows parentheses
foo* my_ptr = new foo;or
foo* my_ptr = new foo();
engineer.cash_check();
engineer->cash_check();
fraction(int n = 0, int d = 1) : numerator(n), denominator(d) {}If the constructor is defined outside of the class, then it would begin with
fraction::
. For large functions, it's common to separate the prototype and the definition. We put the prototype in the class specification in a header file and the definition in a source code file. When we do this, the default arguments go with the prototype, and the initializer list goes with the definition.Foo |
---|
-count : int |
+Foo(a_count : int) |
Some important things to remember:
There are several ways to write the C++ Foo class:
class Foo { private: int count; char my_helper(int arg); public: bool running; Foo(int a_count) : count(a_count), running(true) {} }; |
class Foo { private: int count; public: bool running; public: Foo(int a_count) : count(a_count), running(true) {} private: char my_helper(int arg); }; |
area.h: class area { private: int width; int height; public: area(int w, int h) : width(w), height(h) {} }; area.cpp: area::area(int w = 5, int h = 10) { // a lot of code goes here }What are the three errors in the above code?
alpha alpha::add(alpha a) { return alpha(beta + a.beta); }The highlighted code is only needed if the function is defined outside the class specification.
string getName()
and string get_name()
are both common