Sijith
Sijith

Reputation: 3932

Type casting a structure member

I have structure(A) and it takes another structure(B) as member. Now i want structure C as member of A instead of B. Both B and C are of same type

typedef struct
{
 int a;
 B b;
}A

typedef struct
{
 int a;
}B

typedef struct
{
 int a;
}C

How can i assign struct C as member instead of B. How to do typecasting Please help

Upvotes: 0

Views: 1973

Answers (3)

Sonny Saluja
Sonny Saluja

Reputation: 7287

Without knowing why you want to do this, its hard to recommend a strategy. Here are a few options though.

Option 1: Use Templates. (C++ only)

template <type T>
struct A
{
  int a;
  T* t;
};

struct Foo
{
  int a;
};

struct B : public Foo
{
};

struct C : public Foo
{
};

struct A<Foo> A_foo;

struct B;
struct C;

A_foo.t = &B; //OK! This can now take pointer to any class that extends Foo.
A_foo.t = &C; //OK!

Option 2: Make struct A contain a void* (not recommended, you will lose all type safety). (Both C/C++)

struct A 
{
  int a;
  void* foo; // you can now assign any pointer to foo :-S
};

Upvotes: 1

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

Although they appear to be the same type (and are, in this simple case, identical) they are considered to be different types by the compiler. This makes sense for more complex cases or in C++ where the type system is more complex than in pure C.

You generally shouldn't rely on compiler tricks or hackery to do this sort of assignment. Instead, do it properly. Either directly assign fields or, to simplify code, create a helper function along these lines:

void ASetBWithC(A *a, C c) {
    assert(a != NULL);
    a->b.a = c.a;
}

C++ also has the assignment operator which you could overload to do your work for you (instead of creating a named helper function) but I suspect this is beyond your current comfort level.

Upvotes: 1

watson1180
watson1180

Reputation: 2045

C and C++ are statically typed languages. You can't do it. If you declare something as apple, it will stay as apple until the end of the times.

Upvotes: 2

Related Questions