What is the asterisk in class Department in the private access specifier after the Teacher for?

at line 22.

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
  #include <iostream>
#include <string>
#include <vector>
 
class Teacher
{
private:
	std::string m_name;
 
public:
	Teacher(std::string name)
		: m_name(name)
	{
	}
 
	std::string getName() { return m_name; }
};
 
class Department
{
private:
	std::vector<Teacher*> m_teacher;
 
public:
	Department()
	{
	}
 
	void add(Teacher *teacher)
	{
		m_teacher.push_back(teacher);
	}
 
	friend std::ostream& operator <<(std::ostream &out, const Department &dept)
	{
		out << "Department: ";
		for (const auto &element : dept.m_teacher)
			out << element->getName() << ' ';
		out << '\n';
 
		return out;
	}
};
 
 
int main()
{
	// Create a teacher outside the scope of the Department
	Teacher *t1 = new Teacher("Bob"); // create a teacher
	Teacher *t2 = new Teacher("Frank");
	Teacher *t3 = new Teacher("Beth");
 
	{
		// Create a department and add some Teachers to it
		Department dept; // create an empty Department
		dept.add(t1);
		dept.add(t2);
		dept.add(t3);
 
		std::cout << dept;
 
	} // dept goes out of scope here and is destroyed
 
	std::cout << t1->getName() << " still exists!\n";
	std::cout << t2->getName() << " still exists!\n";
	std::cout << t3->getName() << " still exists!\n";
 
	delete t1;
	delete t2;
	delete t3;
 
	return 0;
}
Last edited on
On line 22 you're declaring a vector of pointers to Teacher objects and you're naming that vector m_teacher.

For more information on pointers, have a look at : http://www.cplusplus.com/doc/tutorial/pointers/
so essentially, that vector now contains the address of each type Teacher object and can be used to push back an element and add another Teacher object?
On lines 49-51 you are creating 3 Teacher pointers, constructing them on the heap.

You then add them to your Department object, lines 55-58, using push_back in the add member function. Lines 29-32.


The non-owning m_teacher vector is destroyed on line 62, but they're still on the heap and accessible from the raw pointers
By default a std::vector stores its data on the heap. Instead of manually managing the memory you can use std::vector's public member functions emplace or emplace_back without the need for the vector to use pointers as the contained data type.

https://en.cppreference.com/w/cpp/container/vector/emplace_back

The vector will take care of properly destroying the elements on the heap when it is destroyed. No manual memory management.

No need to use new or delete.

Notice the example at the link also shows how to construct an object within a push_back, and the extra costs associated with doing that instead of using emplace_back.
Topic archived. No new replies allowed.