Ilonpilaaja
Ilonpilaaja

Reputation: 1239

Wrapper around a class C++

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

Answers (4)

Salvatore Previti
Salvatore Previti

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

John Dibling
John Dibling

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:

  1. You want Foo A; Not Foo::Foo A unless Foo is in a namespace called Foo (which would be bad)
  2. There is no convert constructor declaration.
  3. You aren't using the correct syntax for the initializer list.

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

rchilton1980
rchilton1980

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

Mat
Mat

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

Related Questions