-
Syntax:
class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } variables_with_this_type;-
Classes can be defined not only with keyword
class, but also with keywordsstructandunion.-
structvsclass:-
The only difference between both is that members of classes declared with the keyword
structhavepublicaccess by default, while members of classes declared with the keywordclasshaveprivateaccess by default. For all other purposes both keywords are equivalent in this context.
-
-
The concept of unions is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold member functions. The default access in union classes is public.
-
-
-
OOP is a Dirty Rotten Low Down Trick: A Look at How C++ Works .
-
Very interesting.
-
Methods
-
A method can be defined inside the class, or outside the class by using the scope operator
::. -
The scope operator
::specifies the class to which the member being defined belongs. It's used like an "address/directory", so using:-
My_Class::variable_name, refers to a variable of the classMy_Class. -
::variable_name, refers to a variable in the global scope.
-
#include <iostream>
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {
return width*height;
}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
std::cout << "area: " << rect.area();
return 0;
}
-
The only difference between defining a member function completely within the class definition or to just include its declaration in the function and define it later outside the class, is that in the first case the function is automatically considered an inline member function by the compiler, while in the second it is a normal (not-inline) class member function. This causes no differences in behavior, but only on possible compiler optimizations.
Member Access
-
*x-
pointed to by x
-
-
&x-
address of x
-
-
x.y-
member y of object x
-
-
x->y-
member y of object pointed to by x
-
-
(*x).y-
member y of object pointed to by x (equivalent to the previous one)
-
-
x[0]-
first object pointed to by x
-
-
x[1]-
second object pointed to by x
-
-
x[n]-
(n+1)th object pointed to by x
-
Access Control
-
An access specifier is one of the following three keywords:
private,publicorprotected. -
private:-
Members are accessible only from within other members of the same class (or from their "friends").
-
This is the default access control. Any member that is declared before any other access specifier has
privateaccess automatically.class Rectangle { int width, height; public: void set_values (int,int); int area (void); } rect;
-
-
protected-
Members are accessible from other members of the same class (or from their "friends"), but also from members of their derived classes.
-
-
public-
Members are accessible from anywhere where the object is visible.
-
Constructors
-
Constructors cannot be called explicitly as if they were regular member functions. They are only executed once, when a new object of that class is created, allowing the class to initialize member variables or allocate storage.
-
This constructor function is declared just like a regular member function, but with a name that matches the class name and without any return type; not even void. Constructors never return values, they simply initialize the object.
Constructor Syntaxes
-
Outside the class, with the scope operator
:::class Rectangle { int width, height; public: Rectangle(int,int); int area() { return (width * height); } }; Rectangle::Rectangle(int x, int y) { width = x; height = y; } -
With member initialization, using a
::-
For:
class Rectangle { int width, height; public: Rectangle(int,int); int area() { return (width * height); } }; Rectangle::Rectangle(int x, int y): width(x), height(y) { // empty } -
Initialization Syntaxes
-
They are all equivalent. It's just style.
class_name object_name(value, value, value, ...); // 'functional initialization'.
class_name object_name{value, value, value, ...} // 'uniform initialization'.
class_name object_name = {value, value, value, ...} // 'uniform initialization', POD-like.
class_name object_name = initialization_value; // 'variable initialization / assignment initialization', only allowed for constructors with a single parameter.
Overloading Constructors / Default Constructor
-
The default constructor is the constructor that takes no parameters, and it is special because it is called when an object is declared but is not initialized with any arguments.
-
Empty parentheses cannot be used to call the default constructor.
Rectangle rect_a; // default constructor called Rectangle rect_b{}; // default constructor called using 'uniform initialization'. Rectangle rect_c(); // default constructor NOT called
class Rectangle {
int width, height;
public:
Rectangle ();
Rectangle (int,int);
int area (void) {return (width*height);}
};
Rectangle::Rectangle () {
width = 5;
height = 5;
}
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
int main () {
Rectangle rect_a(3,4);
Rectangle rect_b;
}
Destructor
-
Syntax:
-
Uses the class name as its own name, but preceded with a tilde sign
~. -
It takes no arguments and returns nothing, not even void.
class Example { string* ptr; public: // constructors: Example() : ptr(new string) { } // destructor: ~Example() { delete ptr; } }; -
-
They are responsible for the necessary cleanup needed by a class when its lifetime ends.
Copy Constructor / Copy Assignment / Move Constructor / Move Assignment
"Rule of 5"
-
If a class manages resources and defines one of these:
-
destructor
-
copy constructor
-
copy assignment
-
-
Then it should probably also define:
-
move constructor
-
move assignment
-
class A {
public:
A(const A&);
A& operator=(const A&);
A(A&&);
A& operator=(A&&);
~A();
};
Operator Overloading
-
Syntax:
type operator sign (parameters) { /*... body ...*/ } -
Example:
CVector CVector::operator + (const CVector& param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}
Friend Functions (C++98)
-
Friends are functions or classes declared with the
friendkeyword. -
A non-member function can access the private and protected members of a class if it is declared a
friendof that class. That is done by including a declaration of this external function within the class, and preceding it with the keywordfriend:
#include <iostream>
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) : width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};
Rectangle duplicate(const Rectangle& param) {
Rectangle res;
res.width = param.width*2;
res.height = param.height*2;
return res;
}
int main () {
Rectangle foo;
Rectangle bar (2,3);
foo = duplicate (bar);
std::cout << foo.area() << '\n';
return 0;
}
-
The duplicate function is a
friendof class Rectangle. Therefore, function duplicate is able to access the members width and height (which are private) of different objects of type Rectangle. -
Neither in the declaration of duplicate nor in its later use in main, function duplicate is considered a member of class Rectangle. It is not . It simply has access to its private and protected members without being a member.
Friend Classes (C++98)
-
Similar to friend functions, a friend class is a class whose members have access to the private or protected members of another class:
#include <iostream>
class Square;
class Rectangle {
int width, height;
public:
int area() {return (width * height);}
void convert (Square a);
};
class Square {
friend class Rectangle;
private:
int side;
public:
Square (int a) : side(a) {}
};
void Rectangle::convert (Square a) {
width = a.side;
height = a.side;
}
int main () {
Rectangle rect;
Square sqr (4);
rect.convert(sqr);
cpp:cout << rect.area();
return 0;
}
Inheritance
-
Syntax:
class derived_class_name: public base_class_name { /*...*/ }; -
Examples:
class Rectangle: public Polygon {}; class Rectangle: public Polygon, public Output {}; class Triangle: public Polygon, public Output {};
Virtual Members, Abstract Class
-
The syntax for a function to become virtual is to precede its declaration with the
virtualkeyword. -
A class that declares or inherits a virtual function is called a polymorphic class.
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b) { width=a; height=b; }
virtual int area () { return 0; }
};
class Rectangle: public Polygon {
public:
int area () { return width * height; }
};
class Triangle: public Polygon {
public:
int area () { return (width * height / 2); }
};
Pure Virtual Functions and Abstract Classes
-
Abstract Classes are classes that can only be used as base classes, and thus are allowed to have virtual member functions without definition (known as pure virtual functions).
virtual int area() = 0;
-
Classes that contain at least one pure virtual function are known as abstract base classes.