C++ Classes and Objects
#include <iostream>
using namespace std;
class Rectangle {
private:
int length, width;
public:
Rectangle() : length(1), width(1) {} // default constructor
Rectangle(int l, int w) : length(l), width(w) {} // parameterized
Rectangle(const Rectangle &r) { // copy constructor
length = r.length; width = r.width;
}
~Rectangle() { cout << "Destroying " << length << "x" << width << endl; }
int area() const { return length * width; }
};
int main() {
Rectangle a, b(4, 5), c = b;
cout << a.area() << " " << b.area() << " " << c.area() << endl;
return 0;
}
1 20 20
Destroying 4x5
Destroying 4x5
Destroying 1x1
Order of destructionObjects are destroyed in the reverse order of their creation.
Access Specifiers
| Specifier | Same class | Derived class | Outside |
|---|---|---|---|
| private | Yes | No | No |
| protected | Yes | Yes | No |
| public | Yes | Yes | Yes |
static Members and friend Functions
#include <iostream>
using namespace std;
class Counter {
static int count; // shared by all objects
int secret = 42;
public:
Counter() { count++; }
static int getCount() { return count; }
friend void peek(const Counter &c); // friend can access private members
};
int Counter::count = 0;
void peek(const Counter &c) { cout << "secret = " << c.secret << endl; }
int main() {
Counter a, b, c;
cout << Counter::getCount() << endl;
peek(a);
}
3
secret = 42
Track your progress through the C++ course