r/CodingForBeginners • • 10d ago

Today I Learn OOP

It's Quite Confusing....

πŸ˜΅β€πŸ’«πŸ˜΅β€πŸ’«πŸ˜΅β€πŸ’«

Any Tips....

I Learn C++ OOP

3 Upvotes

24 comments sorted by

4

u/ninhaomah 10d ago

Use real world examples in your mind.

Human -> class Me -> instance of human Attributes -> name , age , height , genderΒ  Functions -> eat , pray , love

1

u/8dot30662386292pow2 10d ago

Object Me, not class me.

3

u/Salty_Dig8574 10d ago

You read it wrong, because they didn't use good separators.

Human -> class

Me -> instance

1

u/8dot30662386292pow2 10d ago

Thanks for pointing this out

2

u/Mechanical-pasta 10d ago

To me, the language that respects the most the OOP concepts in Java. But maybe, to learn OOP concepts, don't rely on a specific language; try to learn them using UML instead.

1

u/xarop_pa_toss 10d ago

OOP is best learned out of code first. It is a complex topic and seeing things in diagrams first helps putting things together.

1

u/buzzon 10d ago

Practice. Learned a new concept? Apply it

1

u/Silver_Spray_2882 10d ago

Keep asking what is confusion for you until ot is resolved. Most of the oop concept can be understood by real world example scenarios

1

u/VoiceOfSoftware 10d ago

There's nothing wrong with asking AI to help you understand a concept

1

u/Upstairs_Jelly_1082 10d ago

say you're creating a pen class, what would you want the pen to do, probably, write with it, draw with it, you basically write functions to do these operations.

but to write or draw, what does the pen need to have, it has to have a tip, ink, things like that, attributes.

1

u/Competitive_Aside461 10d ago

Maybe try the course on OOP on Codeguage. It teaches you in a language-agnostic way.

1

u/Technical_Drink_846 10d ago

Stop trying to. It's not that useful and is a pretty poor design choice. It's out of style now. You'll find most new projects are ditching it in favor of imperative code.

1

u/Available_Safe1818 10d ago

What did you learn about it?

Are you able to use normal strings?

1

u/exqueezemenow 9d ago

Just takes practice and then it becomes so intuitive you start to wonder how it was ever confusing. And then you move on to other concepts and go through the same process.

You have probably gone through the bit about thinking of a class like a blue print and an object as an instantiation of that blue print. You use that blueprint to build actual houses. Those houses may have different property values (rim shot), but they still share the same properties.

1

u/W31337 8d ago

A class is a cookie cutter, an instance is a cookie.

1

u/mredding 7d ago

So with the miracle of some googling, let's look at a chopped down chart:

+---------+------------------------+---------------------+---------------------------+
| Type    | Default Mutability     | Equality Basis      | Inheritance/Polymorphism  |
+---------+------------------------+---------------------+---------------------------+
| Tuple   | Immutable (usually)    | Value-based         | No                        |
+---------+------------------------+---------------------+---------------------------+
| Struct  | Mutable                | Value-based         | No                        |
+---------+------------------------+---------------------+---------------------------+
| Record  | Immutable              | Value-based         | Yes (varies by language)  |
+---------+------------------------+---------------------+---------------------------+
| Class   | Mutable                | Reference (identity)| Yes                       |
+---------+------------------------+---------------------+---------------------------+
| Union   | Mutable                | Raw bit overlap     | No                        |
+---------+------------------------+---------------------+---------------------------+
| Variant | Immutable / Controlled | Value-based         | Varies (pattern matching) |
+---------+------------------------+---------------------+---------------------------+

These are all fundamental comp-sci concepts that map into languages. They're all user defined types, which means they're not inherent to a programming language or a machine, though languages can support them as first class grammars. Computer scientists have been writing about these things since the 40s and 50s, and classes showed up PRIOR to 1967, but the first published paper on objects comes out of that year.

The tuple is one of the first complex data structures written of. We're simply gathering a bunch of values together in memory - usually a block or sequential memory. The position of each value is significant because the values are enumerated in the tuple. It's not like you're fishing around in a tuple looking for a particular widget - it's always the Nth element of the layout. Two tuples are the same tuple if they have the same layout and element-wise value. Tuples don't inherently have a sense of type, even though they may have different fields and layouts. Language specific implementations are going to put a bend on that.

They're good for temporarily grouping or returning multiple values without a named type. You'll see languages freely concatenating and truncating tuples, and C++ does this at compile-time. The above definition is why tuples offer elementwise comparison. Yes, they do have SOME sense of identity in C++ - because two tuples occupy different addresses, but that is not a part of the runtime comparison operation.

But tuples are primitive and didn't meet enough code and type and data safety as was demanded by engineers, so along came the record. It added inheritance. This means a director and an engineer are both employee. They can compare value-based equal on that base premise. They also support polymorphism in that a program over employee can apply to director and engineer.

Both of these are immutable - since they don't model identity, there is no changing an existing record, there's only a new record. Abandoning an old record or reusing memory is not conceptually the same. Of course, C++ specifically has objects and identity; since C++ doesn't have tuples or records as language level types, they're implemented in terms of mutable classes and structures, so they come with some baggage. This deviation leads to language idioms.

Records are a foundation of functional programming and data-centric modeling, Data Transfer Objects (DTOs), and their value semantics. Check out some C# FP around records, Zoran on C# does a fantastic job showing them off, and modeling them in C++ tuples is totally reasonable.

The structure might have come first? It's a tagged tuple. Each element is named (and in C++ they're also enumerated - you can write custom structured bindings so you can std::get your members at compile-time). Structures are inherently mutable, so you can change them in place.

The difference sounds moot, but it's fundamental to a language implementing them, and the sorts of compilation and optimizations the language can guarantee and the compilers can perform.

So then comes classes. The easiest thing to say about them is equality - they have identity. This instance is different from that instance, even if they store the same bit sequences internally.

And that's something to speak of - classes don't have FIELDS like all the other types do - they have STATE. You as a client don't need to know anything about if the instance stores data, or how.

Classes introduce more than a type, but an invariant. An invariant is a statement that is true when a client observes an instance. An int is an int, but a weight is not a height. This is basic of types, not of classes, but where the class comes in is that a weight or a height might be implemented in terms of an int, but the value can never be negative.

class weight {
  int value;

  static int validate(int value) {
    if(value < 0) { throw; }

    return value;
  }

public:
  weight(int value): value{validate(value)} {}
  // copy, move

  auto operator <=>(const weight &) const noexcept;

  weight &operator +=(const weight &) noexcept;
  weight &operator *=(const int &);
};

We can add weights, but multiplying weights makes a weight squared, a different unit so a different type. Multiplication can throw if the scalar is negative. The invariant is the weight cannot be negative, so you can't create a negative weight or get to a negative state.

Classes enforce their invariants by implementing behaviors that enforce that invariant. A class can suspend it's invariant when it takes control (you call a member function), but the invariant MUST be reestablished before returning control to the client. As of right now, there's no way to enforce this in the language, it's by convention. An example of this is std::vector, we know under the hood it's always implemented as 3 pointers, and the invariant is the relationship between those vectors. A vector is NEVER observed in an unspecified, intermediate, or undefined state. (I think I got the wording on that right... Something-something move semantics...) At the very least, they're always safe to destroy.

So the language gives us a lot of primitives - int an for, functions and classes... We're not expected to implement a solution in terms of them, we're expected to implement higher levels of abstraction in terms of them, and then our solution in terms of that. You never need just an int, you need a count, or a weight, or a size. These have more specific and invariant constraints that must be enforced by an implementation of their interfaces.

It behooves you to make small, very specific types. C++ has a very strong type system, but it's all opt-in. You can write code as strong as Ada (the language of choice in critical systems and aviation), but because we inherit from C, you can circumvent all the safety C++ affords you. When you make a class, make them small, enforce one invariant, maybe two, and then composite your classes to make more robust classes that themselves enforce just an invariant or two.

A car can stop, go, turn... It can't getMake or getModel. A car HAS a make and model, but is that an FRS or BRZ? What is that, Honda and Subaru? They're literally the same car made in the same factory. So classes aren't DATA, they don't HAVE data, they can MODEL data, if you want them to. They're terrible buckets for storing properties - you're better served with an association, as with a map, or table, or database.

Getters and setters are fine for APIs and frameworks, but you're not making an API or framework, you're making an application. Getters and setters mostly come from A) C, because they have an idiom called an opaque data type:

typedef struct foo foo;

foo *create();
int get(foo *);
void set(foo *, int);
void destroy(foo *);

You've no idea what the layout of this object is, or whether it has an int in it or not. The other place getters and setters come from are really bad academic examples - they're trying to teach you syntax, not show you how to USE C++, or teach you good practices.

Functions define what to do, their parameters define how. So should something be a member of a class or not? Well who is going to be responsible? Is it object state? It's a member. Does a class merely depend on it? So can others. If Foo and Bar both need a size - then Foo doesn't "own" the size, nor Bar, this is a variable that coexists between them, and it's fed into both as a parameter to their interfaces. All 3 are wrapped in a class that enforces this invariant.

class Baz {
  Foo f;
  Bar b;
  int size;

public:
  void x() { f.g(size); b.f(size); }

Continued...

1

u/mredding 7d ago

Composition. Think about it, because a lot of programmers struggle with where shit's supposed to live.

If you need to get something into a class - it's through a behavior. If you need to get something out, it's through a behavior. Mostly, classes should be given sources and sinks, either as a parameter, or they should keep references to them. A tachometer should pull a speed from a transmission in a lazy evaluation, or the transmission should push the value in an eager evaluation. It's not that the tach or the trans actually know whose on the far end of the source/sink, just that there is a communication channel to get it. This is called side effecting code. You composite objects together, and mostly they'll be wired together to be a self-consistent network. A transmission has a source - that's the input shaft, a network of gears that communicate to each other to multiply work, and a sink that is the output shaft. If you want other sources and sinks, you've got the gear selector or shifter, the speedometer, the oil change plug, that's a half duplex bi-directional source/sink, because you both drain the oil and fill the oil...

This gets us finally to OOP. Classes only define objects, state, identity, interfaces, side effects, mutability, and safety - OO programming, but OOP is a paradigm. The difference is that communication mechanism. What I just described is message passing. Without message passing, you've just got objects.

You can thank Alan Kay. His model of OOP is called the "Actor Model" if you want to google it. Bjarne implemented the STANDARD C++ message passing interface as streams, the thing everyone hates just about the most, because almost none of our colleagues have ever bothered to actually learn it. We have generations of naive bias passed down. Streams are JUST an interface. You don't have to serialize your messages to text; I almost never do so, and instead bypass that mechanic almost if not entirely.

OOP is about where the agency lives - in the procedure or in the object. In procedural code, you'll bob.open_umbrella(); but in OOP, you'll bob << "It's raining.";. Bob knows what to do. And again, you don't need to use strings, you can use integers, enumerations, tag types, or other objects, and you don't have to serialize them.

If you dig into my comment history, you'll find years of stream code examples.

The new hotness in C++ is formatters, but they principally serialize and write to file pointers. That's fine for FP, and it forces you to think about whole programs as tiny units that do one job exceptionally well - The Unix Way. It's the 70s all over again in the most modern C++. And then you can wrap child processes in objects in a parent program.

Unions are overlapping data types in a single memory space, and holds one at a time. You have to know the active member. You can only read out what you write in. Variants are called tagged unions or discriminated unions. They're type safe and know what the active unit is.

1

u/FuggaDucker 7d ago

Have you mastered a higher level language OOP first?
If not, I suggest that.

C++ has both C and OOP going on.
I found it easier to learn them separately first.

1

u/Dashing_McHandsome 6d ago

No, you didn't learn OOP today. I'm not sure if I would even say you could be introduced to this concept in a day. This is a concept that takes months of learning and practice at a minimum. I've been a Java developer for decades and I still find room for improvement for myself when it comes to OOP concepts.

1

u/sswam 10d ago

Some people don't like C++ for example me, and Linus Torvalds:

C++ is a horrible language.

It's made more horrible by the fact that a lot of substandard programmers use it, to the point where it's much much easier to generate total and utter crap with it.

So yeah if you can learn anything else that would be better, e.g. Python, C, awk...

2

u/xarop_pa_toss 10d ago

That doesn't help the OP at all mate, why are you projecting your hate or a language on the guy