Post

[Mastering Data Structures and Algorithms] Classes, Scope Resolution, and Templates in C++

Udemy

Online course lectures up to the 30th

1. Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# include <iostream>
using namespace std;

class Arithmetic
{
private:
		int a;
		int b;
public:
	Arithmetic(int a, int b)
	{
		this->a=a;
		this->b=b;
	}
	int add()
	{
		int c;
		c = a + b;
		return c;
	}
	int sub()
	{
		int c;
		c = a - b;
		return c;
	}
};

int main(void)
{
	Arithmetic ar(10,5);
	
	cout<<"Add "<<ar.add()<<endl;
	cout<<"Sub "<<ar.sub()<<endl;
	return 0;
}

Reviews

  • Constructor Arithmetic (int a, int b) which takes two integer parameters a and b and initializes the member variables a and b.

    • this -> a : It means this is variable

    • this -> a = a : It is a parameter

  • In the main() function, an object of the Arithmetic class named ar is created with the values (10, 5) passed to the constructor

2. Scope Resolution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# include <iostream>
using namespace std;

class Arithmetic
{
	private:
		int a;
		int b;
	public:
		Arithmetic(int a, int b);
		int add();
		int sub();
};

Arithmetic::Arithmetic(int a, int b)
{
	this->a=a;
	this->b=b;
}
int Arithmetic::add()
{
	int c;
	c = a + b;
	return c;
}
int Arithmetic::sub()
{
	int c;
	c = a - b;
	return c;
}

int main(void)
{
	Arithmetic ar(10,5);
	
	cout<<"Add "<<ar.add()<<endl;
	cout<<"Sub "<<ar.sub()<<endl;
	return 0;
}
  • Scope resolution operator in C++ is ::

  • For example, Arithmetic::Arithmetic(int a, int b), It tells the compiler that this functions (Arithmetic, add, sub) are the member of the Arithmetic class

3. Template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# include <iostream>
using namespace std;

template<class T>
class Arithmetic
{
	private:
		T a;
		T b;
	public:
		Arithmetic(T a, T b);
		T add();
		T sub();
};

template<class T>
Arithmetic<T>::Arithmetic(T a, T b)
{
	this->a=a;
	this->b=b;
}

template<class T>
T Arithmetic<T>::add()
{
	T c;
	c = a + b;
	return c;
}

template<class T>
T Arithmetic<T>::sub()
{
	T c;
	c = a - b;
	return c;
}

int main(void)
{
	Arithmetic<int> ar(10,5);
	Arithmetic<float> ar1(10.5,5.3);
	Arithmetic<char> ar('a','b');
	
	cout<<"Add "<<ar.add()<<endl;
	cout<<"Sub "<<ar.sub()<<endl;
	return 0;
}
  • The class T within the angle brackets < > is a placeholder for the data type
This post is licensed under CC BY 4.0 by the author.