I'm continuing my studies for uni with C++ and I'm running into some serious comprehension issues concerning pointers, const arguments and all the very basics of class implementations (which are so easy in Java compared to C++)
I usually work with Java, so C++ is very new to me.
This is my simple header for a class "Person":
#ifndef Person_h
#define Person_h
class Person
{
private:
char* name;
char* adress;
char* phone;
public:
Person();
Person(char const *name, char const *adress, char const *phone);
Person(const Person &other);
~Person();
void setName(char const *name);
char* getName() const;
void setAdress(char const *adress);
char* getAdress() const;
void setPhone(char const *phone);
char* getPhone() const;
};
#endif // !Person_h
And here the problem starts. Why should I use char pointers instead of actual char variables? I'm guessing it's some conventions to spare memory or to improve performance?
This is the way our professor codes and tries to make us understand the use of pointer and const
etc.
Now here's my implementation of the class:
#include "Person.h"
//Person.h class implementation
Person::Person()
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
}
Person::Person(const char *name, const char *adress , const char *phone)
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
setName(name);
setAdress(adress);
setPhone(phone);
};
Person::Person(Person const &other)
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
setName(other.getName);
setAdress(other.getAdress);
setPhone(other.getPhone);
};
Person::~Person()
{
delete [] name;
delete [] adress;
delete [] phone;
};
void Person::setName(const char *name)
{
this->name = name;
};
char* Person::getName() const
{
return name;
};
void Person::setAdress(char const *adress)
{
this->adress = adress;
};
char* Person::getAdress() const
{
return adress;
};
void Person::setPhone(char const *phone)
{
this->phone = phone;
};
char* Person::getPhone() const
{
return phone;
};
We should learn to manually allocate memory to elements and try to take care of the overall memory management. Therefore the use of const arguments for the setter functions. I guess this is in order to not alter the element argument? I'm very confused, basically...
And my IDE (MS VisualStudio 2015) underlines the following line as error:
void Person::setName(const char *name)
{
this->name = name; //error
};
"a value of type 'const char *' cannot be assigned to an entity of type 'char *'"
Then why should I use const
when I can't assign these values? Or how can I "un-const" those, without making the member variable itself const
?
This whole matter is just one big confusion to me now.
EDIT: I have to use C-strings for my exams, that's in order to understand pointer and memory management referring to our prof.