Saturday, April 17, 2010

Structures and Classes in c++

struct keyword is facing the downside in comparison of class because of its strong attachment to the legacy C code.
But most people ignore the fact that structs have been totally reinvented in c++.

The only difference between struct and class in c++ is that by default everything is public in structs and private in classes, even the default inheritance in struct is public.

thats all the difference between structs and classes, then why in recent programming practices structs have been totally ignored.

structs can be safely initialized using constructors, they can have polymorphic nature, support late binding, in short everything you need to write good OO code.


check out the code given below.

#include
using namespace std;

struct Whatever
{
virtual void foo() { }
virtual ~Whatever() { }
};

struct Derived : Whatever
{
void foo() { cout << "value=" << value; }
Derived(int n) : Whatever(), value(n) { }

private:
int value; // private data member
};

int main()
{
Whatever *pW = new Derived(10);
pW->foo(); // virtual call
delete pW;
return 0;
}


IMHO struct are fighting a loosing battle because of the mindset of the developers, We have been taught C++ means classes, C++ even started out as "C with classes".
anything which needs an aggregate data type can be implemented using structs and anything needed as a complex data type adhering to OOPS principles, representing some real world object needs to be implemented in terms of classes.

There is no problem in using classes or structs for that matter, just need to open our minds to the realities of C++ , rather than following and believing in myths.

No comments:

Post a Comment