A class is a template which defines the entities we want to model by combining data representation and methods for manipulating that data into one package.
We can create many different instances of a class which have property values which are different from each other even though they come from the same template.
A class can be instantiated both on the stack and the heap, but they most commonly instantiated on the heap.
Classes on stack vs heap
class Colour {private:string name;int r, g, b;public:Colour() {
name = "";
r = 0;
g = 0;
b = 0;
}}
//declare and create instance
0x0061ff00
0x0061ff04
""
Colour favColour;
string name;
0x0061ff08
0x0061ff0c
0
int r;
0x0061ff10
0
int g;
0x0061ff14
0
int b;
0x0061ff18
0x0061ff2d
rtn addr
0x0061ff1c
0
rtn val
Stack
class Colour {private:string name;int r, g, b;public:Colour() {
name = "";
r = 0;
g = 0;
b = 0;
}}
//declare pointer and create instance
0x0061ff0c
0x0061ff10
0x001d54f4
Colour *favCol;
0x0061ff14
0x0061ff18
0x0061ff2d
rtn addr
0x0061ff1c
0
rtn val
Stack
Heap
0x001d54f0
memory leak!
0x001d54f4
""
string name;
0x001d54f8
0x001d54fc
0
int r;
0x001d5500
0
int g;
0x001d5504
0
int b;
0x001d5508
Classes on stack vs heap - delete
class Person {private:string name;int age;public:Person() {
name = "";
age = 0;
}}
0x0061ff00
0x0061ff04
0x001d54f4
Person *jack;
0x0061ff08
0x0061ff0c
""
Person jill;
string name;
0x0061ff10
0x0061ff14
0
int age;
0x0061ff18
0x0061ff2d
rtn addr
0x0061ff1c
0
rtn val
Stack
Heap
0x001d54f0
0x001d54f4
""
string name;
0x001d54f8
0x001d54fc
0
int age;
0x001d5500
0x001d5504
0x001d5508
class Person {private:string name;int age;public:Person() {
name = "";
age = 0;
}}
0x0061ff0c
0x0061ff10
0x001d54f0
Person *jack;
0x0061ff14
0x0061ff18
0x0061ff2d
rtn addr
0x0061ff1c
0
rtn val
Stack
Heap
0x001d54f0
""
String name;
0x001d54f4
0x001d54f8
0
int age;
0x001d54fc
0x001d5500
""
String name;
0x001d5504
0x001d5508
0
int age;
0x001d550c
0x001d5510
Default vs Explicit constructors
class Person {private:string name;int age;public:Person() {
name = "";
age = 0;
}Person(const string &name, int age) {this->name = name;this->age = age;}}