When it comes to creating classes I’ve been told NO public data members. That’s fine and I understand why but here’s my issue. I’ve got a struct that I am using in a class (Linear linked list). I’d really like to initialize one of the struct fields (an array) to NULL so that I can check that the client is passing me valid structs, not uninitalized one’s that are full of garbage values. I realize c++ won’t let me set a default value in the struct declaration, so how do I protect from the client giving me garbage?
struct task {
char *description;
char *name;
float time_remaining;
float time_spent;
};
Then in my class I’m trying to do something like:
//I am making a copy of "to_add" and storing it in the LLL
int list::add_to_list(const task & to_add)
{ /.../ }
I don’t want the user adding a bunch of uninitialized “task’s” to the linked list… What to do? When I turned that struct into a class and moved the data members to private I had a TON of issues trying to access the data members to make copies of them. I was very careful not to do anything to effect the value of the var’s but I couldn’t get away from the compiler giving me errors about “error: passing ‘const task’ as ‘this’ argument of ‘char* task::get_comp_name()’ discards qualifiers [-fpermissive]” (“get_comp_name”) was one of the getter’s that I was sure wasn’t editing any values, just passing me a copy) Please help me before I shoot myself. In the face.
In C++ a
structand aclassare the same except for access control. So the struct’s default access to members and inheritance is public, whereas the class’ one is private. So you can give your struct a defult constructor and others to initialize it.One side-effect of adding a constructor is that the struct isn’t an aggregate anymore. This may or may not be an issue for you.
In C++11, you are also able to initialize members at the point of declaration:
This in-place initialization accepts
type x = ysyntax too, and argument-less{}initialization results in value initialization, which results in zero initialization for primitive types, so the arguments in the example could have been omitted.