-2

So I am having trouble with the following syntax in c++:

I am developing a c++ program on windows and using visual studio 2022. It is a simple console application using c++20.

I have the following class structure:

Class1 {
    Class2 function();
}

Class2 {
    Class1 function2();
}

Class1 Class2::function2() {
...
}

Class2 Class1::function1() {
...
}

This is only an example, and I know I can separate them into two files, I already tried it. I can not program these functions inline, because they are using the constructors of the other classes, so I can't just define them inside their own classes. I get a linker error.

Here is my exact problem:

class first_class {
public:
    int some_other_func() {
        return 0;
    }
    second_class upgrade();
};

class second_class {
public:
    int some_func() {
        return 0;
    }
    first_class downgrade() noexcept;
};

first_class second_class::downgrade() {
    ...
}


second_class first_class::upgrade() {
    ...
}

This all should be in one header file. But when I try to compile it, I get LNK2005 and LNK1169.

Norbi
  • 67
  • 1
  • 6

1 Answers1

2

The code shown does not compile, let alone link.

Class1/first_class is trying to use Class2/second_class before the latter has been declared. You need a forward declaration to fix that, eg:

class second_class; // <-- add this!

class first_class {
public:
    // NOW you can use second_class here...
};

class second_class {
public:
    ...
};

Also, second_class::downgrade() is declared as noexcept, but is not defined as noexcept. You need to add noexcept to the definition:

first_class second_class::downgrade() noexcept {
                                      // ^ add this!

After fixing those two mistakes, the code compiles and links for me:

https://godbolt.org/z/6oEd4vTcP

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770