Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Problem w/ classes in C (http://www.go4expert.com/forums/classes-c-t16812/)

Earl Kulog 6Apr2009 07:49

Problem w/ classes in C
 
Hey guys out there! Hope we're all just fine today. Wanna help me some problem? Here it is...

In C++, you write a code something like this:

class CMyClass {
public:
CMyClass();
~CMyClass();
int m_attrib;
private:
static LONG m_privAttrib;
};

And you define it and access its members like this:

LONG CMyClass::m_privAttrib;

CMyClass::CMyClass()
{
...
...
}

CMyClass::~CMyClass()
{
...
}

But I can't write my code that way in C. I love C being a straightforward language but I love the way I used to in writing my classes in C++. Is there some work around to bail me out of this problem?

Malaking pasasalamat.

shabbir 6Apr2009 08:35

Re: Problem w/ classes in C
 
You submitted the query as article and I have moved it to forum for discussion.

Also there is a difference in C and C++ which you have to accept it.

xpi0t0s 6Apr2009 13:35

Re: Problem w/ classes in C
 
It's harder to use classes in C because the language doesn't fully support object programming.
But you can do object-style programming; use struct instead of class and you can create an "object" with member functions and attributes. I don't think C supports private or protected struct members, and it certainly doesn't support the virtual keyword so good luck with your manual implementation of the virtual function table. C also doesn't support overloaded function names or operators, and for proper object-style encapsulation you'll have to limit yourself to one class per C file and use "static" a lot. And lots of void pointers. And by the way there is no "this" pointer in C.

So while you can do object oriented programming in C it definitely won't be the same way you write C++ programs, unless you get some kind of C++ to C precompiler (which is all C++ was in the early days; I think Bjarne called it "C with classes"), and if you're going to do that then you may as well stick with the C++ compiler.


All times are GMT +5.5. The time now is 03:13.