hey coders, sorry as i am fairly new to c++ but i have a private map in a class, I am trying to initialise the map to be empty when the constructor of the class is called e.g.
//Student.h
Class Student:
public:
private:
map <string, float> marks;
//Student.cpp
Student::Student()
{
//my attempt which throws an error
map<string, float> Student::marks;
}
I have searched but cant find a solution, am I meant to initialise it using initialisation lists within the constructor?
It will be default initialized to be empty, you don't have to do anything special.
If you wanted to explicitly default initialize it, you would something like:
1 2 3
Student::Student()
: marks{}
{ }
Otherwise, you don't even need to define a constructor.
Edit: Note that in your code as it looks right now, your default constructor is private. Not sure if that's intentional. Edit 2: Oh wait, you don't actually show the declaration, nevermind.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Example program
#include <iostream>
#include <string>
#include <map>
using std::map;
using std::string;
class Student {
public:
map <string, float> marks;
};
int main()
{
Student sally;
sally.marks["History"] = 3.2f;
}
If you don't define any custom constructors for your class, then compiler defines a default constructor for it implicitly.
That constructor "calls the default constructors of the bases and of the non-static members of this class". https://en.cppreference.com/w/cpp/language/default_constructor
1 2 3 4 5 6 7 8 9 10
#include <map>
class Student {
std::map<char,int> dict;
};
int main() {
Student poet; // Calls default constructor, which calls default constructor of dict
// assert: poet.dict.size() == 0
}
ahh okay it is called by default, I want to explicitly initialise it for the sake of my assignment, the student class is a derived class, whats the correct syntax for this
1 2 3 4 5 6 7 8 9 10 11
//Student.cpp
Student::Student(const string &name, int regNo)
:Person(name)
// I tried ( :Person(name), : dict() )
//but I got a compiler error
{
}
Hi, there I am also new to c++ and must say I am so surprised about all its options and abilities. Also, I see it so great to use for student`s storage, guess it is so useful, I hope I will practice working with it and will be able to do it by myself. By the way, if you are students I will ask if you have ever use https://www.aresearchguide.com/cheap-essay-writing-service.html this service while studying at college or university? I mean, if you have looked here for cheap essay writing service, was it good?