Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all
I have a struct that is used in its following class
and my class is base of two other class
I want to know if I can forward declare the struct and have different definition of that in my two child header

What I have tried:

smilar to this
//base header
struct forw;
class Base
{
    
}
//header child 1
struct forw
{
   int a;
   char b;
}
class child1::Base
{
}
//header child2

//header child 1
struct forw
{
   int a;
   int c;
}
class child2::Base
{
}
Posted
Updated 29-Dec-18 19:52pm
v2
Comments
KarstenK 30-Dec-18 4:19am    
Work with different struct and with pointers to them. It is better to be precise, as Griff told. Or you will learn it "the hard way" (by having strange bugs). ;-)

1 solution

Not a good idea, not at all.
Yes you can do it, provided the two child classes are in separate files. But ... it's a very bad idea as the two structs may have different "physical" sizes (in this case, they don't, since the first one will be "rounded up" to a multiple of 32 bits anyway). And when you have different sizes, you will start messing with data that is outside the struct when you use it. That can lead to very unpredictable results, from random data corruption to application crashes.

Don't do it. Just because you can do something, doesn't mean you should...
 
Share this answer
 
Comments
saide_a 30-Dec-18 1:58am    
actually I want that different physical size
OriginalGriff 30-Dec-18 2:03am    
No, you don't - it'a bad idea. If you want different sizes, then call them different things. Otherwise you will get unpredictable effects going on, and they are very hard to work out and fix later on.

Why do you think you want that?
saide_a 30-Dec-18 2:26am    
I have a packet and my packet implementation is different in my child classes
and, in my base class I used this packet too,
then I am going to define it in this way
#define FRAME_PACKET_TYPE(buff) (*((uint8_t*)&buff[0]))
thanks
OriginalGriff 30-Dec-18 2:37am    
Don't - use a union in your struct instead:
https://www.tutorialspoint.com/cprogramming/c_unions.htm
That way, the memory allocation required for the struct will always be correct: it will be the largest allocation it needs regardless of where you create it.

It's also a whole load less confusing when you read it back for maintenance in six months time...

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