Why Have Functions() in classes?

Pages: 12
Why Have Functions() in classes? As a C only programmer trying to learn C++ I don't understand why functions() are defined inside of classes? Why is this different than C structs? How is their usage different othen than having to use the classname.function() format to call them?
Last edited on
As a C programmer you should ignore/forget a lot of what you learned how to program when learning C++. Even the C++ standard library, outside of its C version, is handled in ways different than how things are done in C.

Why do classes have methods? Encapsulation of logic. Tightly bind the encapsulated data and the functioning that manipulates the data into a singular package.

Object Oriented Programming.

Learn C++ is a free online tutorial website that might help the transition easier:
https://www.learncpp.com/

Note: one of the core ideas that sets C++ apart from C, object-oriented programming, is addressed in Chapter 13, the earlier 12 chapters deal in non-OOPish aspects of variable types, functions and the like.

I'd suggest you start at the beginning, Chapter 1, and plow your way through as if you were learning to program with no prior experience.
Last edited on
closed account (G21UpDi1)
C programmers can do object oriented programming.

Last edited on
it is a great question.
There are many tiers of answers, as you progress through the tools c++ has to offer.
At the beginner level, the answer starts with simply code organization and parameter passing.
the class has member variables, just like a C struct, ok?
but a function in C to work on the struct must have the struct passed into the function as a parameter. In c++, normal member functions (called methods in modern books) will have access to the struct variables directly, so many functions will not have ANY parameters because the data it needs is already accessible. Code is also organized: the methods that belong to a class are scoped to it (the :: operator) so you can have 20 classes all with a "printme()" (bad example, but roll with it) method of the same name and the compiler has no problem with that, each one is scoped to its type and so the name conflict is handled automatically. Also the code is typically a header and Cpp file per class (or 2-3 small classes if tightly coupled can be in the same file if they are all small and need each other to function)

At the second tier of understanding, there is operator overloading.
if you make a matrix struct in C, then multiplication of 3 matrices might look like this:
m = matrixmultiply(c, matrixmultiply(a, b));
in c++ it might look like this:
m = c*(a*b);
and it gets worse and worse the more complicate the expressions become when doing advanced math that requires objects as types (sets, matrices, vectors, complex numbers, fractions, for some examples).

Beyond that you will encounter overriding of virutal functions. That is where a class can leave a function empty for the user to provide the body for their own special purpose, used with inheritance so that a new object can be derived from an existing one, with slight modifications to specific functions but mostly reusing the other object's code easily.

There are more reasons too, but this is enough to get started. Much will become clear as you study more, but for now, maybe trust that there are good reasons that make things work very cleanly once you get past the beginner stage where, indeed, it really is little more than a syntax change from C.

**
print is a good example because everyone knows what a print function should do, but its a bad example because objects often supply a friend method to ostream so that cout will print correctly for that object, and it may also be virtual, so the user can customize the printing. But pretend that its a good idea to provide a beginner's approach to that where your function just calls cout on the member variables and use that as a simple example of a member function, you can see how letting the user override that to print them in another order or with more decimal places or different text (maybe change the language used) etc is useful?
Last edited on
The mind set of programming is vastly different for C vs. C++, though there is overlap.

The question the OP asked shows they are thinking in C terms, not how they should think in C++.

What's the default way to generate floating point random numbers in C? Can it be done natively with the C standard library functions in a couple of lines of code?

Easy to do in C++ with C++11's <random> library.
"Defined" as in implemented or just as declared?

Functions as in constructors/assignment/move/destructor/operators or just as other function?


Some do suggest that one should prefer non-member non-friends, when designing interface of a class.
@DickFulthorp Why Have Functions() in classes?

A class in C++ is used to implement several different ideas. But in general it groups things together.

For example, the ANSI C file data structure is a FILE*. And there are many functions that do stuff with files; fopen, fseek, ftell, fread, fwrite, fclose, ... , all of which take that FILE* as an argument. However, no one cares what's in a FILE*. An Abstract Data Type can hide that implementation detail, just present the methods, and hide the implementation. That's one use of a C++ class.

@robertb C programmers can do object oriented programming.

You can, but there's no language support for it, so the programmer has to do all the heavy lifting; an error prone and relatively inefficient process.

Last edited on
closed account (G21UpDi1)
@kbw

Please correct me if I'm wrong.

An object is a named location in memory that can be referenced.

That's the definition I use. If you use that definition a function and a struct are both objects. And as an aside both are also modular.

So if you code with a focus on objects your method is by definition OOP.

In my opinion OOP is just a buzzword and has no meaning anymore.
Last edited on
Let's see what Sainted Bjarne Stroustrup has to say about OOP:
https://www.stroustrup.com/bs_faq.html#oop

It isn't just a buzzword, but it has been used and misused for a long, long time.
closed account (G21UpDi1)
@george

An appeal to authority is a classic fallacy.

The definition I'm using for obect comes from the book: "Programming: Principles and Practice Using C++," as close as I can remember. (I'm aware of my hypocrisy)

Rhetorical question: if you program in C++ using classes to create objects, but do not define the classes are you using OOP.
Last edited on
The question(s) the OP asked were good questions deserving of answers. I'm not here to debate or argue about picayune minutiae.

Pax
@robertb
An object is a named location in memory that can be referenced.
The term object is used to describe different things in different contexts.

If you're concerned with memory layout, linking differnt object files together and so on, then yes, your definition holds.

But that isn't what an object is when discussing object oriented programming.
Last edited on
robertb wrote:
Please correct me if I'm wrong.
robertb wrote:
An object is a named location in memory that can be referenced.

This sounds more like the definition of what a variable is. Not all objects have names.


robertb wrote:
The definition I'm using for obect comes from the book: "Programming: Principles and Practice Using C++,"
Programming Principles and Practice Using C plus plus 2nd edition wrote:
To read something, we need somewhere to read into; that is, we need somewhere in the computer’s memory to place what
we read. We call such a “place” an object. An object is a region of memory with a type that specifies what kind of information can be placed in it. A named object is called a variable.


robertb wrote:
If you use that definition a function and a struct are both objects.

According to the C++ standard a function is not considered an object.
The Standard wrote:
Note: A function is not an object, regardless of whether or not it occupies storage in the way that objects do.
https://eel.is/c++draft/intro.object#note-1
Last edited on
closed account (G21UpDi1)
Thank you Peter, I appreciate the work you put into your replies.

To tell the truth I read that book in 2008 and was recalling that definition by memory. I'm not surprised I severely corrupted his wording.

Place in memory is much more accurate than a named location. I will use that wording in the future.

So according to the standard C++ does not recognize a function as an object. It's authoritative so my argument is obviously wrong within the C++ universe.

robertb wrote:
It's authoritative so my argument is obviously wrong within the C++ universe.

It's authoritative in how C++ should work but not necessarily in the way we talk about it.

My favourite example of why I think so is the term "member variable". The standard calls them "data members" and does not consider them to be variables at all (except for static ones). I still think "member variable" is a perfectly good thing to call them because conceptually I think most of us think about them as variables.

Another example is "final", "module" and "override" not being keywords. The standard calls them "Identifiers with special meaning" but if I tell some one to use the "override keyword" is that such a bad thing?

I think if we insisted to follow the standard wording to the letter every time we discussed something about C++ we would drown in needless details and complications (and few would be able to do it properly). Often we can use the words a bit more loosely and still be able to understand what is meant, based on context and experience. I'm probably too strict in my choice of word myself sometimes (e.g. feeling bad about calling std::sort a function) but it obviously depends on the nature of the discussion. If you're discussing a language proposal with a C++ language expert you probably should use a language that is more strict to what the standard uses but if you're just helping a beginner such language might just make it harder to understand what you're saying.


The "C++ universe" (as you called it) is not really a separate universe with no connection to other universes. The word object exists in English where it has a broader meaning. You also have the word object in OOP which is not specific to C++. That makes multiple definitions of the same word hard to avoid.

It's not uncommon to talk about OOP concepts without any particular programming language in mind. A C++ programmer might discuss OOP programming with a Java programmer. The code might look a little different depending on the language but it's still basically the same OOP. It doesn't fundamentally change just because the programming language happens to define the word object differently.

Trying to call it something else (e.g. Item Oriented Programming - IOP) when discussing OOP inside the "C++ universe" (e.g. on this forum) would probably cause more confusion than it prevents.


Using a definition of the word object that includes functions is mainly "wrong" because it's uncommon and doesn't seem to have much reason to exist (except maybe if you want to be able to say all pointer types point to objects, even function pointers) and would therefore likely only lead to confusion if it was used.

The OOP definition of object is less problematic because all those objects would still be considered to be objects with the C++ standard definition so calling them objects is not wrong by any definition. What might happen is that people might get confused the first time they see someone refer to a non-class object as an object. I think this is a minor problem.
Last edited on
Why is this different than C structs?

The C++ class has access control that C struct does not. You can write:
1
2
3
4
class Sample {
public:
  // members
};

Or, more conveniently:
1
2
3
struct Sample {
  // members
};

These you can use just like C structs; any function can read&modify "fields of these objects".

What C++ adds are the protected, private, and friend.
These make members inaccessible for unrelated functions and emphasize the use of class via its interface.
I am reading through all these "helpful" replies getting more confused than I was to start with. My main issue is with the semantics. C++ users tend to talk using all the proper C++ names for things, but beginners like me need to have things defined in terms of what they already know, not in terms of other concepts they do not yet understand. My experience with Computers started in 1959 at the University of Washington as a freshman. They had a IBM computer that required Fortran for students with punch cards etc. so I have had 60+years of ASM, Fortran and C, on embedded microprocessors. An electrical engineer who never did and electrical engineering but went straight into programming after getting a BSEE degree. When I read about C++ I see words like inheritance and polymorphism and immediately go to sleep because there is no meaning defined.
Inheritance and polymorphism can't be explained by virtually anything a C programmer has knowledge of, because C++ isn't C. That is like asking how to build a jet plane when one knows only paper airplanes.

If you are bored by C++ then maybe it isn't for you. There's no shame in knowing one's limitations and interests. C can be just as recondite and abstruse about its jargon.

Because of the breadth of what C++ has in the programming toolbox compared to C it has a much steeper learning curve, sometimes explaining key parts with at the time other bits that are just as unfamiliar.

If you want to learn about such arcane esoterica you could poke your nose around a free online tutorial, Learn C++.

https://www.learncpp.com/
meh :P
polymorphism in c ... if the first part of 2 'objects' (typedefed structs) is identical then pointers to them can be interchanged such that they both can represent the smaller object correctly.
c++ takes that a little farther and smarter, but its a starting point.

inheritance is more tricky beyond has-a. Its already aggravating to make a method with a function pointer, and passing that up a chain just gets that much more goofy.

Its a round peg square hole problem, just like trying to make java do something without objects. If you want objects, use a language that supports it. If you don't want objects, use a language that lacks them. If you want both, use a hybrid (c++ being one, if not absolutely the best of the best at both worlds).

I don't mind seeing C++ without objects. There is a place for free floating functions that just do things. That is, after all, what std <algorithm> really is: useful functions that don't have to be glued to a class to work.
Last edited on
When I read about C++ I see words like inheritance and polymorphism and immediately go to sleep because there is no meaning defined.


These terms are the crux of OOP. If you are interested in learning C++, you absolutely must learn what these concepts are. They are extremely powerful tools for the programmer to use. Those terms are soooo central to OOP that they won't be defined unless the the paper/book is geared for beginners. It would be kind of like using the term "loop" or "struct" in a paper for C programmers. Context is not needed unless it's being written for beginners.

A story: I used to work at a strong "C" company that was migrating to C++. I was working on a project where billing information was generated based on the service provider, country, etc.

We started by providing billing information for 1 setup. A few days later we got the go-ahead to generate billing information for a second setup. My coworkers imagined combing through the code and looking for all sorts of places to put in if (billType == TYPE1){} else if (billType == TYPE2){} checks to make sure the correct bits were generated for each billing type. This would be a tedious and complex process, especially as more and more setups were added.

They were all surprised when I was able to use the power OOP and come up with a second billing implementation in an afternoon. The original code for the first billing type was completely untouched. Inheritance from a common base class and polymorphic behavior when calling a billing function made this dreaded job simple.

As @jonnin said, it might have been possible to do this with function pointers and pointers to overlapping structures. But the tools that OOP (and C++) provide can be very powerful and cut through a lot of the goofiness.

I am not here arguing that classes and objects are the be-all and end-all of programming. I'm just saying that they are very powerful tools for your toolbox if you decide it's worth it to learn and understand them.

I'm 57, and while not actively contemplating retirement, it's on my radar. I don't know how much bandwidth I would want to spend learning a new programming language right now. You have been programming longer than I've been alive. If you want to better understand C++ and OOP (and I highly recommend you do), you need to invest some time learning about these terms that put you to sleep. And with your decades of programming experience and the habits you've developed, you will have a non-trivial obstacle to overcome when learning the OOP paradigm. Only you can determine if the juice is worth the squeeze. I hope you determine it is.

The learncpp.com site was mentioned above. Alternately, this site has a tutorial that can give some basics on classes. (https://cplusplus.com/doc/tutorial/ - focus on the topics under "Classes"). The tutorial on this site is not up-to-date on the latest C++ standards, but will be more than sufficient for understanding these basic concepts.

And when you have more questions, we're still here. We look forward to answering sincere questions.
Pages: 12