Getting exception when trying to access class member with address

0

I am trying to access class variable that created in heap with address in C++.

#include <iostream>
#include <string>

using namespace std;
class class2 {
private:
    string String = "x";
public:
    void function() {
        cout<<String;
    }
};

class class1 {
public:
    class2* i;
        void  address(class2* x) {
        i = x;
    }
};



int main() {
    int len;
    cin>>len;
    class1 **Class1 = new class1*[len];

    for(int i = 0; i < len; i++) {
        Class1[i] = new class1[i];
    }

    Class1[0]->address(Class1[0]->i);
    Class1[0]->i->function();

}

void function() {
        cout<<String;
    }

if I change this to this I get no errors and it works fine. So I thought there is a problem about accessing string variable.

void function() {
        cout<<"x";
    }

Exception thrown: read access violation. std::_String_alloc > >::_Get_data(...) returned 0xDDDDDDDD.

UPDATED CODE:

class class2 {
private:
    string String = "x";
public:
    string function() {
        return String;
    }
};

class class1 {
public:
    string String;
    class2* i;
        void  address(class2* x) {
        x = new class2();
        i = x;
    }

        void function(string x) {
            String = x;
    }
};



int main() {
    int len;
    cin>>len;
    class1 **Class1 = new class1*[len];

    for(int i = 0; i < len; i++) {
        Class1[i] = new class1[i];
    }

    Class1[0]->address(Class1[0]->i);
    Class1[0]->function(Class1[0]->i->function());
    cout<<Class1[0]->String;

}

Exception thrown at 0x0F4D514F (vcruntime140d.dll) in Project70.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD.

c++
asked on Stack Overflow Oct 15, 2019 by oldBear • edited Oct 15, 2019 by oldBear

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0