0
votes

I had made 2 class in my project. I want to use a function from 1st class to the 2nd class the problem is I can't instantiate the 1st class to the 2nd class. By the way both classes were declared in different headers.

here is a sample code:

header 1:

class 1stclass{
   public:

   2ndclass *class2;
   void function1(QString parameter1)
   {
       QString str1;
       list = class2->function2(parameter1);
   }
};

header 2:

class 2ndclass{
   public:

   QString function2(QString parameter2)
   {
       QString str2 = parameter2 + "hello"; 
       return str2;
   }
};

I want to use the function in function 2 but it gives me an error. here is the error message:

  1. ISO C++ forbids declaration of '2ndclass' with no type;
  2. expected ';' before '*' token;
  3. 'class2' was not declared in this scope;
3
Do you include header file for 2ndclass into header file for 1stclass?beduin
Was it included before the code for the 1stclass (i.e. at the top)?mlvljr

3 Answers

5
votes

Class names aren't allowed to start with a number in C++.

Class1 and Class2 are valid names though.

0
votes

The compiler does not know anything about the second class when trying to create the pointer. Didn't you forget to include the header file with the second class declaration? Is the file included in your qt project file or Makefile? By the way, the first character of an indetifier can't be a number, only a-z and underscore.

-1
votes

Why don't you use a .cpp file. The first class can't know what 2ndclass is unless you include the header.

Header 2:

class SecondClass
{
public:
    QString function2( const QString &parameter2 );
};

Cpp 2:

SecondClass::function2( const QString &parameter2 )
{
  // your func
}

Header 1: You can include header2.h or use a forward declaration like

class SecondClass;

class FirstClass
{
public:
    QString function( const QString &parameter );

    SecondClass *s2;
};

Cpp 1:

#include "SecondClass.h"

FirstClass::function( const QString &parameter )
{
    s2 = new SecondClass;
    QString str1;
    list = s2->function2(parameter1);
}