2

So i have a header and source file containing an implementation for a vector. I want to use the vector to implement a heap. So I realized that I would want my functions to be specific to the class so I declared each one as static thinking I could do Vector::get(int n, Vector::Vector* vector) but apparently :: is not an operator in C and static just makes things private. Can anyone help me understand how I can make the correct encapsulation and not name all my get functions Heap_get or Vector_get?

user93353
  • 13,733
  • 8
  • 60
  • 122
Brian Crafton
  • 438
  • 2
  • 6
  • 15
  • 1
    `Vector::get` I'm afraid that isn't valid C code. Please be aware of the differences between C and C++. – Ryan Apr 30 '15 at 03:47
  • 1
    I'm afraid that in C, `Vector_get()` and `Heap_get()` is exactly the way one proceeds.... In C, there is no name mangling as in C++. Naming is fully the responsibility of the programmer. – Iwillnotexist Idonotexist Apr 30 '15 at 03:47
  • 1
    For better or worse, using a unique prefix is the most common way of providing context, a namespace in C, if you will. – R Sahu Apr 30 '15 at 03:52
  • 1
    If you don't mind being weird and nonstandard, you could create a `struct` of function pointers. – AnotherParker Apr 30 '15 at 03:54
  • 2
    @AnotherParker That's not entirely unrealistic; It's exactly how C++ vtables and OpenCL ICD are implemented. Each object's first element is a pointer to a function dispatch table, from which the concerned function is invoked with the object pointer as the first argument. – Iwillnotexist Idonotexist Apr 30 '15 at 04:01

1 Answers1

3

C++ has namespaces and class specifiers to distinguish between things like that but, in C, names have to be unique.

It's a time honored tradition to simply use a (generally short) prefix for your code and hope you never have to integrate code from someone else that has used the same prefix.

So names like vecGet() or heapCreate() are exactly the way C developers do this.

Now you can do polymorphism in C but it's probably overkill for what you're trying to do.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Ah okay, well if that is that standard. Thank you for all for the quick, helpful responses. – Brian Crafton Apr 30 '15 at 04:02
  • Well, _defacto_ standard. It's not like ISO _mandates_ you have to do it that way. They _do_ mandate the uniqueness of names however. – paxdiablo Apr 30 '15 at 04:09