Unknown size of Foo in Bar.cpp!

Discussion in 'C++' started by Jason Heyes, Jun 30, 2005.

  1. Jason Heyes

    Jason Heyes Guest

    Why does Foo.h need to be included in Bar.cpp for this program to compile
    properly? I define the FooList destructor in a separate module so that a
    forward declaration to Foo can be used.

    // FooList.h

    #include <vector>

    class Foo;

    class FooList
    std::vector<Foo> v;

    ~FooList(); // destructor interface

    // FooList.cpp

    #include "FooList.h"
    #include "Foo.h" // destructor definition this

    FooList::~FooList() { }// destructor definition

    // Bar.cpp

    #include "FooList.h"

    int main()
    FooList foos;
    return 0;

    Error Message

    c:\program files\microsoft visual studio\vc98\include\vector(59): error
    C2036: 'Foo *': unknown size
    c:\program files\microsoft visual studio\vc98\include\vector(58): while
    compiling class-template member function 'vector<Foo>::~vector<Foo>(void)'

    I don't want to include Foo.h in Bar.cpp unless I have to. Do I have to? If
    so, why? Thanks a bunch.
    Jason Heyes, Jun 30, 2005
    1. Advertisements

  2. But you don't include the definition of 'Foo' here either. You have to!
    Yes, you have to. But you only need it in 'Bar.cpp', not in 'FooList.h'.

    Victor Bazarov, Jun 30, 2005
    1. Advertisements

  3. Jason Heyes

    Jason Heyes Guest

    Weird. Bar doesn't look like it even uses Foo. All that happens in Bar.cpp
    is a call to FooList::FooList and a call to FooList::~FooList, both of which
    are defined in a separate module FooList.cpp. So aren't these just calls to
    external functions?
    Jason Heyes, Jun 30, 2005
  4. It has to allocate memory for 'FooList', doesn't it? How much to
    allocate? So, it needs to instantiate 'std::vector<Foo>' for that,
    don't it? So, to instantiate, it needs to know hat 'Foo' is, right?

    Victor Bazarov, Jun 30, 2005
  5. The problem is that FooList::~FooList() isn't responsible for calling the
    destructor function vector<Foo>::~vector(). The vector destructor gets called
    after ~FooList() has completed it, so ~vector() needs to be instantiated in
    the block of main() { }. If you used vector<Foo>* instead, then you'd be
    able to "hide" the destruction inside ~FooList(), but that almost defeats the
    purpose of using vector in the first place.

    Donovan Rebbechi, Jun 30, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.