I'm trying to access a member structs variables, but I can't seem to get the syntax right. The two compile errors pr. access are: error C2274: 'function-style cast' : illegal as right side of '.' operator error C2228: left of '.otherdata' must have class/struct/union I have tried various changes, but none successful.
#include <iostream>
using std::cout;
class Foo{
public:
struct Bar{
int otherdata;
};
int somedata;
};
int main(){
Foo foo;
foo.Bar.otherdata = 5;
cout << foo.Bar.otherdata;
return 0;
}
You are only declaring Foo::Bar but you don't instantiate it (not sure if that's the correct terminology)
See here for usage:
Here you have just defined a structure but not created any object of it. Hence when you say
foo.Bar.otherdata = 5;
it is compiler error. Create a object of struct Bar likeBar m_bar;
and then useFoo.m_bar.otherdata = 5;
You create a nested structure, but you never create any instances of it within the class. You need to say something like:
You can then say:
You only define a struct there, not allocate one. Try this:
If you want to reuse the struct in other classes, you can also define the struct outside:
Bar
is inner structure defined insideFoo
. Creation ofFoo
object does not implicitly create theBar
's members. You need to explicitly create the object of Bar usingFoo::Bar
syntax.Otherwise,
Create the Bar instance as member in
Foo
class.