-2

I have defined a struct in class. Then defined a function that returns address pointer type obj of struct it is working but when I created three file structure it is now giving an error "variable undefined" LIKE

/// header file

class A {
    struct b{
    };
    b *var;
public:
    b *&f1();
};
//// cpp file
b A:: *&f1()
{
    return var; /// here it gives an error saying "var undefined" 
}

can any one please help me :)

Barmar
  • 741,623
  • 53
  • 500
  • 612
Hamza Azam
  • 302
  • 1
  • 4
  • 9
  • 4
    What `b A:: *&f1()` is supposed to mean. The syntax of the method definition outside of the class definition is of form: ` :: () { }`. Return type of your method is `A::b*&`, the class name is `A`, and the method name is `f1`, i.e.: `A::b*& A::f1 () { ... }`. Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Algirdas Preidžius Jan 05 '18 at 20:34
  • Don't forget indentation. This code is slammed left and is really a jumble. – tadman Jan 05 '18 at 20:53

2 Answers2

0

The struct b is declared within the namespace of the A class. That's why the return value of the f1() method in the source file has to be prefixed with the A class namespace resolution: A::b.

class A {
      struct b {};
      b *var;

     public:
     // normaly you would also do something like this
     A() : var(new b) {}
    ~A() { delete var; }

      b*& f1();
    };
    //// cpp file
    A::b*& A::f1() {
      return var;  /// here it gives an error saying "var undefined"
    }
StPiere
  • 4,113
  • 15
  • 24
  • 1
    Your definition of such a function, doesn't match OPs intent - they want to return a reference to `var`. – Algirdas Preidžius Jan 05 '18 at 20:38
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. – Makyen Jan 05 '18 at 21:31
0

You need to define the function as:

A::b*& A::f1()
{
return var; /// here it gives an error saying "var undefined" 
}
SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23