Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
class A{
int a;
};

int A::a=10;
and
C++
class A{
int a=10;
};
The former is valid but latter is not. I don't understand— what is the difference between them when compiling?

What I have tried:

Asking my friend, Asking chatgpt, Google
Posted
Updated 2-Mar-24 19:55pm
v2
Comments
Betey 2-Mar-24 22:42pm    
Sorry for the mistake. I mean the former is invalid but the latter is valid.

THis is a simple question, but the answer is kinda complicated.
When you try to compile the first version:
C++
class A{
int a;
};

int A::a=10;
Youi will get an error message telling you that "a is not a static member of class A" and that is absolutely accurate - but unless you understand classes, instances, and static variables / methods it's not really helpful.

There are two types of "elements" that a class can have: static elements, and instance elements (where an element is a field, property, method, event, or delegate)

A static element is shared by all instances, and is accessed via the class name.
An instance element is unique to each different instance of the class and is accessed via the variable holding the instance reference. Which doesn't seem to make more sense either - but it does and you are very, very aware of this in the real world!

Think about cars for a moment: all cars have a colour - but which colour it is depends on which specific car you are talking about. My car is black; your car is red; this car is green; that car is blue. Colour is an instance property of the Car class because you need to have a specific instance of a Car in order to ask the question "what colour is it?" - you can't say "what colour is a car?" because it's meaningless without saying which car you mean.
But cars have static properties as well: you can ask "how many wheels has a car?" because all cars have four wheels. (If it had two, it would be a motorbike, not a car)

What your first example is trying to do is "set the colour of all cars" which is impossible; your second is trying to "set the colour of this specific car" which is very possible!

Make sense so far?
 
Share this answer
 
Comments
CPallini 4-Mar-24 2:30am    
5.
There are two problems with the invalid assignment of the member variable:
C++
class A {
    int a;
};

int A::a = 10;

Non-static data members may not be defined outside their class, as they belong to a concrete object, while static elements belong to the class. In this case, the member variable is also declared multiple times, which also cannot work.
 
Share this answer
 
Comments
CPallini 4-Mar-24 2:30am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900