Search code examples
c++classoopdata-structuresconstructor

Addresses of array in default constructor is same but on printing comes out to be different


#include<iostream>
#include<string.h>
using namespace std;
class Student{
    int age;
    
    public:
    char *name;
    
    
    
    Student(int age,char *name){
        this->age = age;
        
        this->name = new char[strlen(name) + 1];
        strcpy(this->name,name);

    }
    void display(){
        cout<<this->age<<" "<<this->name<<endl;
    }
};

int main(){
    char name[] = "abcd";
    Student s1(20,name); 
    Student s2(s1);
    s2.name[0] = 'e';
    //s2.name = "abdd";
    cout<<&name<<endl;
    cout<<&s1.name<<endl;
    cout<<&s2.name<<endl;
    s1.display();
    s2.display();
}

OUTPUT :-

0x61ff0b
0x61ff04
0x61fefc
20 ebcd
20 ebcd

Why the addresses of s1.name and s2.name are different and still changes in s2.name is affecting s1.name??


Solution

  • You're printing the address of the pointer variable rather than the value of the pointer itself.

    We can simplify your example to:

    char name1[] = "abcd";
    char* name2 = name1;
    std::cout << &name1 << "\n";
    std::cout << &name2 << "\n";
    

    This will print two different addresses of the two different variables but we still only have one array.

    If you want to print the address of the array you need to cast to void* as the stream operator deliberately prints the contents of the null terminated string when passed a char*:

    std::cout << static_cast<void*>(name1) << "\n";
    std::cout << static_cast<void*>(name2) << "\n";
    

    To fix your code you'll need to implement a copy constructor, assignment operator and destructor, see What is The Rule of Three? or more simply just use std::string which does all of that for you.