-2

Let's say I have the following:

char cipan[9];

then what should I pass to the function? how about the get and set method??

I'm currently doing like this

set method

void setCipan(char cipan[]){

this->cipan = cipan;
}

and the get method

char getCipan(){
return cipan;
}

and I get an error when compiling??

Im totally blur.. can someone explain what should i pass to the function??

    class userData{
private:
    string name;
    char  dateCreate[9];

    void userDataInput(string name,char dateCreate[]){
        this->name = name;
        this->dateCreate = dateCreate;

    }
public:
    //constructor
    userData(string name){
        userDataInput(name,dateCreate);
    }
    userData(string name,char dateCreate[]){
        userDataInput(name,dateCreate);
    }
    //mutator methods
    void changeName(string name){this->name = name;}
    void changeDateCreate(char *dateCreate){this->dateCreate = dateCreate;}
    //accesor methods
    string getName(){return name;}
    char *getDateCreate(){return dateCreate;}


};
Iqbal
  • 246
  • 2
  • 10

2 Answers2

1

I'd do the following:

void setCipan(const char* new_cipan)
{
    strcpy(cipan, new_cipan);
}

const char* getCipan() const
{
    return cipan;
}

Of course, the better approach is to use std::string:

void setCipan(const string& new_cipan)
{
    cipan = new_cipan;
}

string getCipan() const
{
    return cipan;
}
Donotalo
  • 12,748
  • 25
  • 83
  • 121
1
  • Constructor's purpose is to initialize class variables. I think it's unnecessary to call another method in the constructor to do initialization.


void userDataInput(string name,char dateCreate[]){
    this->name = name;
    this->dateCreate = dateCreate; // Both the dateCreate are class variables.
}

userData(string name){
    userDataInput(name,dateCreate); // dateCreate is already a class variable.
}

dateCreate is the class scope variable. You are just passing it to a method, and re-assigning the same to dateCreate. Assignment operation doesn't copy elements of one array to another and are invalid operations.

To copy array elements, use std::copy instead.

Mahesh
  • 34,573
  • 20
  • 89
  • 115