Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Class or Struct compatiblity with C struct

Is it possible to write a C++ class or struct that is fully compatible with C struct. From compatibility I mean size of the object and memory locations of the variables. I know that its evil to use *(point*)&pnt or even (float*)&pnt (on a different case where variables are floats) but consider that its really required for the performance sake. Its not logical to use regular type casting operator million times per second.

Take this example

Class Point {
    long x,y;
    Point(long x, long y) {
        this->x=x;
        this->y=y;
    }

    float Distance(Point &point) {
        return ....;
    }
};

C version is a POD struct

struct point {
    long x,y;
};
like image 668
Cem Kalyoncu Avatar asked Sep 15 '09 20:09

Cem Kalyoncu


People also ask

Is it better to use struct or class?

Class instances each have an identity and are passed by reference, while structs are handled and mutated as values. Basically, if we want all of the changes that are made to a given object to be applied the same instance, then we should use a class — otherwise a struct will most likely be a more appropriate choice.

Is struct in C same as class in C++?

The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.

Is struct in C same as class?

Struct has limited features. Class is generally used in large programs. Struct are used in small programs. Classes can contain constructor or destructor.

Why do we need class if we have struct?

Using a struct we can achieve all the functionality of a class : constructors (that can be modified/overloaded), destructors (that can be modified/overloaded), operator overloading, instance methods, static methods, public / private / protected fields/methods.


1 Answers

The cleanest was to do this is to inherit from the C struct:

struct point
{
    long x, y;
};

class Point : public struct point
{
  public:
    Point(long x, long y)
        {    this->x=x; this->y=y; }

    float Distance(Point &point)
        {                return ....;        }
}

The C++ compiler guarantees the C style struct point has the same layout as with the C compiler. The C++ class Point inherits this layout for its base class portion (and since it adds no data or virtual members, it will have the same layout). A pointer to class Point will be converted to a pointer to struct point without a cast, since conversion to a base class pointer is always supported. So, you can use class Point objects and freely pass pointers to them to C functions expecting a pointer to struct point.

Of course, if there is already a C header file defining struct point, then you can just include this instead of repeating the definition.

like image 128
Stephen C. Steel Avatar answered Sep 22 '22 21:09

Stephen C. Steel