views:

28

answers:

4

I've got a simple class, and another class that has a property that points to the first class:

#include <iostream>
#include <vector>

using namespace std;

class first{
public:
    int var1;
};

class second{
public:
    first* classvar;
};

Then, i've got a void that's supposed to point "classvar" to the intended iteration of the class "first".

void fill(vector<second>& sec, vector<first>& fir){
    sec[0].classvar = &fir[0];
}

Finally the main(). Create and fill a vector of class "first", create "second" vector, and run the fill function.

int main(){

    vector<first> a(1);
    a[0].var1 = 1000;

    vector<second> b(1);

    fill(b, a);

    cout << b[0].classvar.var1 << '\n';

    system("PAUSE");
    return 0;
}

This gives me the following error:

1>c:\...\main.cpp(29) : error C2228: left of '.var1' must have class/struct/union
1>        type is 'first *'

And I can't figure out why it reads the "classvar" as the whole vector instead of just the single instance. Should I do this

cout << b[0].classvar[0].var1 << '\n';

it reads perfectly.

Can anyone figure out the problem? Thanks in advance

A: 
cout << b[0].classvar->var1 << '\n';

b[0].classvar is a pointer. Your current code should be valid with that fix, but make sure you don't invalidate the pointer later.

Matthew Flaschen
A: 

The problem is that b[0].classvar is a pointer. To access members of a class through a pointer, you must use the -> operator, not ..

The reason b[0].classvar[0].var1 works is because the index operator [] for pointers makes this equivalent to (*(b[0].classvar + 0)).var1. In other words, it adds 0 to the pointer and then dereferences it, so you can then access it with the dot operator.

Nick Meyer
A: 
b[0].classvar->var1
Marc
A: 

This

cout << b[0].classvar.var1 << '\n';

should be

cout << b[0].classvar->var1 << '\n';

since second's classvar is a pointer to first.

This

b[0].classvar[0].var1

works due to the equivalence of pointers & arrays in C & C++.

Eugen Constantin Dinca