pointer to an inherited member

cplusplus forum,

I have a pointer problem/question.

class BASE
{
public:
string str[10];
string str1[10];
};

class Inherited : public BASE
{ public: };


I'm trying to construct an array of pointers to the strings in the
inherited class.

string *pnt[2];
string BASE::pnt[0] = &Inherited.str;
string BASE::pnt[1] = &Inherited.str1;

But the compiler gives me errors like:

"initializing cannot convert from string *" and
"cannot be used to initialize an entity of type string"

I've read all I could find on the net but can't find the answer.

Any suggestions/solutions?
jerryd

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

class BASE
{
public:
std::string str[10];
std::string str1[10];
    
};

class Inherited : public BASE
{
    public:
    std::string* pnt1 = str; // = this -> etc
    std::string* pnt2 = str1;
};
And if you like, to see how that works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

class BASE
{
public:
    std::string str[10]{"aa", "bb", "cc"};
std::string str1[10];
    
};

class Inherited : public BASE
{
    public:
    std::string* pnt1 = str; // = this -> etc
    std::string* pnt2 = str1;
};

int main()
{
    Inherited in;
    std::cout << in.pnt1[1] << '\n';
    return 0;
}


bb
Program ended with exit code: 0
I'm trying to construct an array of pointers to the strings in the inherited class.
If you mean an array of pointers to all the strings then you could do this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>

class BASE
{
public:
    std::string str[10];
    std::string str1[10];
};

class Inherited : public BASE
{
public:
    std::string *allStrings[20];
    Inherited();
};

Inherited::Inherited() {
    unsigned i=0;
    for (auto &s : str) {
	allStrings[i++] = &s;
    }
    for (auto &s : str1) {
	allStrings[i++] = &s;
    }
}

int main()
{
    Inherited x;
    x.str[4] = "str four";
    x.str1[5] = "str1 five";

    for (unsigned i=0; i<20; ++i) {
	std::cout << "string " << i << ": " << *x.allStrings[i] << '\n';
    }
}
@jerryd
You haven’t specified, or perhaps even considered, how values for the two string arrays are established. Making them public leaves it wide open.

Suffice it to say, doing it through an Inherited object or one of type Base or both might need a closer look beyond what you original question was about.

All the best

Registered users can post here. Sign in or register to post.