Wai Lok Chan
Wai Lok Chan

Reputation: 3

C++ Error: use of undefined type

I have two classes, Friend2 is a friend of Friend1. After Friend2 accesses the Friend1's private member variable, I want Friend1 to be able to access the Friend2's public member functions. So I decided to use composition inside Friend1. However, the compiler shows me the error:

use of undefined type 'friend2'

Then, I tried another way, making Friend1 a friend of Friend2 too. But I still got the same error. Would anyone teach me the way to solve? Thx a lot!

#ifndef FRIEND1_H
#define FRIEND1_H

class friend2;

class friend1 {
  private:
    int x;
    public:
    friend1();

    int comp(friend2* f2o);

    friend class friend2;
    };

    friend1::friend1() {
      x = 1;
    }

    int friend1::comp(friend2* f2o) {
      return f2o->getxx(); //the error : use of undefined type 
    }

#endif


#ifndef FRIEND2_H
#define FRIEND2_H

#include "friend1.h"
#include <iostream>

class friend2 {
  private:
    int xx;
    public:
    friend2();
    void p(friend1* f1o);

    int getxx() const;

    friend class friend1;
    };

    friend2::friend2() {}

    void friend2::p(friend1* f1o) {
      xx = f1o->x;
    }

    int friend2::getxx() const {
      return xx;
    }

#endif

Also, is composition or friend class the better way to do this? Why?

Upvotes: 0

Views: 5280

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

You get //the error : use of undefined type because class Friend2 is only declared, not defined at that point. To solve this move int friend1::comp(friend2* f2o) implementation to friend1.cpp and include friend2.h from there.

UPDATE In general, if two classes are mutual friends (and even if only one of them is a friend to another), it's a good reason to think about the design.

Upvotes: 2

Related Questions