Reputation: 1239
suppose a C++ class has a constructor (among other constructors) of the form
Foo::Foo( FILE *fp ) { etc... }
Now I want create a wrapper class of the form
class WFoo {
Foo::Foo A;
Foo::Foo B;
};
with constructor
WFoo::WFoo(FILE *fa, FILE *fb) {
A(fa), B(fb);
}
What is wrong with the definition of WFoo? Thanks in advance.
Upvotes: 1
Views: 339
Reputation: 9050
This doesn't make any sense...
class WFoo {
Foo::Foo A;
Foo::Foo B;
};
You mean...
class WFoo {
public:
Foo A;
Foo B;
WFoo(FILE* fa, FILE* fb);
};
WFoo::WFoo(FILE* fa, FILE* fb) :
A(fa), B(fb)
{
}
Remember also that fields are initialized not in the order you read in the constructor but in the order they are declared in the class!
So...
#include <iostream>
struct XFoo
{
XFoo(const char* s) { std::cout << s << std::endl; }
};
struct YBar
{
XFoo a;
XFoo b;
YBar() : a("A"), b("B") {}
};
struct ZBar
{
XFoo b;
XFoo a;
ZBar() : a("A"), b("B") {}
};
int main()
{
YBar y;
ZBar z;
return 0;
}
will print out...
A
B
B
A
Upvotes: 9
Reputation: 101446
If the code you've posted is psudocode, then there is nothing wrong with the definition of WFoo
.
If, on the other hand, the code you've posted is not intended to be psudocode, but actual code you'd try to compile & run, then here is what's wrong with WFoo
:
Foo A;
Not Foo::Foo A
unless Foo
is in a namespace called Foo
(which would be bad)This is what you want:
WFoo::WFoo(FILE* fa, FILE* fb)
: A(fa), B(fb)
{
}
Note that the initializer list comes before the body of the constructor.
Upvotes: 1
Reputation: 21
That's an initializer list but the syntax is off. Try:
WFoo::WFoo(FILE* fa, FILE* fb) : A(fa), B(fb)
{
}
Upvotes: 2
Reputation: 206669
The syntax you're looking for is:
WFoo::WFoo(FILE *fa, FILE *fb) : A(fa), B(fb) { ... }
And, unless Foo
is in a namespace called Foo
and WFoo
is not:
class WFoo {
Foo A;
Foo B;
};
Upvotes: 1