Search code examples
c++constructorinitializer-list

How to deep copy in initialization List incase of const variable


I know deep copy in constructor can be done in following way.

class student{
    public:
    int age;
    int rollno;
    char *name; 
    
    
     student(int rollno,int age, char *name){
        this->age=age;
        this->rollno=rollno;


        //deep copy 
        this->name=new char[strlen(name)+1];
        strcpy(this->name,name);
    }
 };

But I wanted to do it using initialization list (in case variables are of const type) This is my new class:

    class student{
       public:
        const int age;
        int rollno;
        const char *name; // used pointer to avoid wastage of space or less space getting assigned 
      
        student(int age,int rollno, char *name): rollno(rollno),age(age),name(name){
            
        }
    };

Now I Am accessing this class in following way

#include<bits/stdc++.h>
#include "student.cpp"
using namespace std;

int main(){

 
    char name[]= "jerry";
    student s(12,1,name);
    cout<<s.name<<endl; //gives jerry
    name[0]='m';
    cout<<s.name<<endl; // gives merry
}

So what i want is that object variable's value should not change. it means it should print jerry in both cout statement. There is similar question but I am not getting that or how to implement in this particular case.


Solution

  • You should be using std::string to store strings.

    With it, your class looks like this:

    class student{
       public:
       const int age;
       int rollno;
       const std::string name; 
      
       student(int age, int rollno, std::string name): 
         rollno(rollno), age(age), name(std::move(name)) {}
    };
    

    Not only does this give you exactly what you want, but on top of that:

    • By using RAII, it also fixes memory leaks present in your original code
    • This will make your code faster and use less memory when dealing with small strings due to some fancy optimizations being done in std::string, so even your "avoid wastage of space" concerns are being addressed.