Search code examples
c++classparameterized

Pass char array to parameterized constructor


class books{
public:
    char* genre;
    books(char *n);
};

books::books(char*n){
    genre = new char[strlen(n)+1];
    strcpy(genre,n);
}

int main(){
   book harrypotter;
   char n[20]; 
   cin>>n;
   harrypotter.books(n);
}

Help me to understand where is my fault? I think i've a lack 'bout pointer :( How to assign n[20] array to *genre member of class ?


Solution

  • A constructor can only be invoked at the time of the declaration of an object. Your constructor looks alright, but the code in main is not.

    int main() {
       char n[20]; 
       cin >> n;
       books harrypotter(n);            // calling parameterized constructor
       cout << harrypotter.genre;      // == cout << n;     
    }
    

    Also, do keep in mind that any memory allocated using new will not be freed until you explicitly do so. Make a destructor to do that.