samprat
samprat

Reputation: 2214

avoid declaring same data types in different structures

I have 2 -3 structures declared in my code and all these structures have some common data type. In our company its strict policy that we do not duplicate code . so I am wondering is there any way that i can declare these common data type in some function and use that function when we declare structure.

example

 struct_1
    {

    ... un common stuff

    // below are common declaration .. how would I declare below data type in some function and
// call it here to declare those data type
    unsigned char char_1;
    unsigned int int_1;
    std::vector< small_structure> small_struct;

    }

struct_2
{

... un common stuff

unsigned char char_1;
unsigned int int_1;
std::vector< small_structure> small_struct;

}

struct_3
{

... un common stuff

unsigned char char_1;
unsigned int int_1;
std::vector< small_structure> small_struct;

}

Upvotes: 0

Views: 84

Answers (2)

user3770240
user3770240

Reputation: 1

you can put all these structures in a header file(xx.h).When you need these structures,you can include these header files,such as ' include "xx.h" '

Upvotes: 0

user694733
user694733

Reputation: 16047

Why not create common struct then?

struct Common {
    unsigned char char_1;
    unsigned int int_1;
    std::vector< small_structure> small_struct;
}

struct struct_3
{
    ... un common stuff
    struct Common commonStuff;
}

Or if you use C++, you could inherit from common struct:

struct struct_3 : Common
{
     ... un common stuff
}

But do prefer composition over inheritance when possible.

Upvotes: 4

Related Questions