Potaito
Potaito

Reputation: 1190

C++: Passing classes as argument to methods of other classes

I want to pass a class pointer to a function which is a member of another class and it won't work. If the function fill_packet is not a member of any class, the code compiles without problems:

// WORKS FINE:

class Packet{
private:
  char *contents;

public:
  void pack();
};

void fill_packet(Packet *a){
  a->pack();
};

However, if the function fill_packet is inside another class (here Worker), it suddenly does no longer compile as soon as I try to access a method of a.

// WON'T COMPILE:
// error: ‘Packet’ has not been declared

class Worker{
public:
  void fill_packet(Packet *a){
    a->pack();
  };
};

class Packet{
private:
  char *contents;

public:
  void pack();
};

Can someone give me insight? thanks in advance

Upvotes: 0

Views: 145

Answers (4)

Radwan
Radwan

Reputation: 26

Be sure that the Packet class is defined before the Worker class, here is a full test:

#include <iostream>

class Packet {
private:
    char *contents;

public:
    void pack() {
        this->contents = "Some text";
    }
    char * getContents() {
        return this->contents;
    }
};

class Worker {
public:
    void fill_packet(Packet *a) {
        a->pack();
    }
};


int main() {
    Packet * packet =  new Packet;
    Worker worker;
    worker.fill_packet(packet);

    std::cout << packet->getContents() << std::endl;

    delete packet;
    return 0;
}

if you run this test you will got the output you expect.

Upvotes: 1

Raxvan
Raxvan

Reputation: 6505

It might be the case where Worker is included somewhere else before the declaration of 'Packet'. To fix this you can tell the compiler that the class Packed exists when you declare 'Worker', and the implementation of 'fill_packet' need to be put somewhere where both classes are declared;

something like this:

class Packet;
class Worker{
public:
  void fill_packet(Packet *a);
};

//in a cpp file:
void Worker::fill_packet(Packet *a){
    a->pack();
};

Hope this helps, Raxvan.

Upvotes: 3

SinisterMJ
SinisterMJ

Reputation: 3509

If your code goes like this

Packet mPacket;
Worker mWorker;
mWorker.fill_packet(&mPacket);

this should work.

On the other hand

Worker.fill_packet(&mPacket);

will not work, unless you declare

class Worker{
public:
  static void fill_packet(Packet *a){
    a->pack();
  };
};

Edit: note, the compiler error doesn't make sense from the code snippet you posted.

Upvotes: 1

Grim Fandango
Grim Fandango

Reputation: 2426

yes, it does compile!

maybe you have defined the class in a header which you did not include?

Upvotes: 1

Related Questions