1

In the past I've been able to forward declare a class as a struct and vice-versa, or to declare the type like in C, like:

void function(struct Foo* arg);
void function(class Foo* arg);

I thought they were the same thing for the purposes of this or forward declaring because I've heard many times that the only difference between a struct and class is the default access specifiers (struct being public default while class is private).

I've changed one word in a class of mine from "struct" to "class" and for the first time I've seen that it breaks my code, the linker says that it can't find a variable of that type that's defined somewhere. Is this not allowed to mix "struct" and "class" in this way?

Zebrafish
  • 11,682
  • 3
  • 43
  • 119

1 Answers1

-3

You sometimes get away with it. And often you don't.

struct, class and namespace are NOT the same. You absolutely DO need to use the correct keyword when forward declaring.

Much to my annoyance, because there's no legal way to forward declare a nested class or struct.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • 3
    The OP didn't ask about namespace, and struct/class *are the same*. Visual Studio may not think so, but the C++ standard does. And forward-declaring nested types has nothing to do with whether `struct` or `class` is the same. – Nicol Bolas May 13 '20 at 15:47
  • @NicolBolas Some programmers seem to think that because their compiler doesn't mark class, struct and namespace as different types, that they're allowed to forward declare nested classes as a class in a namespace. They are wrong but they think "well the compiler allows it it must be OK!" – Zan Lynx May 13 '20 at 22:44
  • @NicolBolas Also even if the standard claims they're equivalent at least one compiler disagrees and in my opinion using the wrong keyword in a forward declaration is *just sloppy* in any case. – Zan Lynx May 13 '20 at 22:45
  • "*Some programmers seem to think that because their compiler doesn't mark class, struct and namespace as different types, that they're allowed to forward declare nested classes as a class in a namespace.*" No programmer thinks that. And no compiler allows you to forward declare a nested class as a class in a namespace. And again, the OP didn't mention namespaces, so I have no idea why you even brought them up. – Nicol Bolas May 13 '20 at 22:51
  • "*Also even if the standard claims they're equivalent at least one compiler disagrees*" ... so what? That doesn't make them right. You can disagree on whether or not it's OK to steal something, but that's not going to be an effective defense at trial. – Nicol Bolas May 13 '20 at 22:53