Object Oriented Programming in C++ and Python
All Episodes
From Structs to Classes: OOP in C++ and Python

From Structs to Classes: OOP in C++ and Python

0:00|0:00
Compare structs, classes, encapsulation, constructors, copying, and Python object basics with a review quiz.

This show was created with Jellypod, the AI Podcast Studio. Create your own podcast with Jellypod today.


Chapter 1

Imported Transcript

Carlos

Welcome to the COP 4020 course podcast. I’m Carlos, your professor and host, and Maya is joining me again. Today we are moving from data organized in structs to objects that combine data with behavior. We will use both C++ and Python to review the central ideas of object-oriented programming.

Maya

So this is not only a syntax comparison. We are asking why we would design a class in the first place.

Carlos

Exactly. By the end, you should be able to distinguish a struct from a class, explain encapsulation and access control, recognize constructors and destructors, and compare how C++ and Python create objects. We will also connect C++ pointers and copying to Python’s object references.

Maya

And do we still end with a quiz?

Carlos

Yes. Five questions, a pause to think, and an answer after each one.

Carlos

Let’s begin with the C++ struct. A struct groups a fixed set of related members, possibly of different types. The lecture uses a house record with fields such as style, number of bedrooms, year built, price, and tax.

Maya

The struct defines a new type, but the variable declaration creates the actual object that stores values. Is that the same distinction we make with classes?

Carlos

Yes. A class definition is a blueprint or user-defined type. Memory for instance data is allocated when we create an object. With either a struct or class object, the dot operator selects a member.

Maya

The slides also place arrays inside structs, structs inside arrays, and even structs inside other structs. Why emphasize those combinations?

Carlos

Because real entities have structure. A list needs both elements and a length. A company may need an array of employee records. An employee record may contain an address record. These examples move us from isolated variables toward modeling a problem domain.

Maya

The slides say that one struct can be assigned to another struct of the same type, but input and output still happen member by member. Why the difference?

Carlos

Assignment has a defined whole-record meaning: the destination receives copies of the source members. Standard input and output do not automatically know how you want a complex record formatted. Should a house print its price first, include labels, or hide its tax? The programmer must define those choices. That limitation points toward classes, where a print or display operation can belong to the abstraction itself.

Maya

Then what does a class add? A struct already groups data.

Carlos

A class packages data together with operations that protect and interpret that data. Instead of letting every client directly change the hour, minute, and second of a clock, the class can provide operations such as setTime and printTime. The object controls how its state changes. That combination of state and behavior is the key step toward object-oriented design. COP 4020 Programming Languages • Unit 3 Podcast ---

Carlos

In C++, class members may be public, private, or protected. Public members form the interface available to client code. Private members can be used directly only by the class’s own member functions. Protected members are also available to derived classes, a topic that becomes more important when we study inheritance.

Maya

Why not make hour, minute, and second public? That would require less code.

Carlos

It would require less code initially, but it would also allow an invalid time such as ninety minutes. Encapsulation lets setTime validate its inputs and preserve the object’s rules. It also lets the internal representation change without forcing every client program to change.

Maya

The lecture calls getHour an accessor and setTime a mutator.

Carlos

Right. An accessor observes state without changing it. A mutator modifies state. In C++, placing const after getHour’s parameter list promises that the method will not modify the object’s instance variables.

Maya

And the method prototypes can stay inside the class while the implementations appear elsewhere?

Carlos

Yes. Outside the class, the scope-resolution operator identifies which class owns the method: Clock double-colon setTime. Separating interface from implementation keeps the public contract visible and hides lower-level details. Each Clock object still receives its own hour, minute, and second values.

Maya

If I pass a Clock object to a function, should I pass it by value or by reference?

Carlos

Pass by value creates a copy, which is appropriate when the function needs an independent object but may cost time and memory. Pass by reference avoids that copy and works with the original object. If the function only needs to observe the clock, a reference to const gives efficiency while preventing modification. The choice communicates both performance expectations and intent.

Carlos

A constructor establishes an object’s initial state. In C++, it has the same name as the class and no return type. A class can overload constructors by providing different parameter lists.

Maya

What happens if I write only the constructor with three parameters and then declare campusClock without arguments?

Carlos

That declaration fails. Once you provide a parameterized constructor, C++ does not automatically supply a no-argument constructor. This also matters for a basic array of objects, because every element typically needs to be constructed before you can assign individual values.

Maya

The slides then shift to pointers, new, and delete. How is that connected to object-oriented programming?

Carlos

Objects often own resources whose lifetime must be managed. A pointer stores an address. The new operator allocates dynamic memory, and delete or delete brackets releases it. A pointer to a struct or class can access a member with the arrow operator. But manual ownership creates risk: forgetting delete causes a leak, while deleting shared memory at the wrong time can leave another pointer invalid. COP 4020 Programming Languages • Unit 3 Podcast ---

Maya

That is where shallow and deep copy appear?

Carlos

Exactly. A shallow copy duplicates the address, so two objects point to the same allocation. A deep copy allocates separate memory and copies the contents. For a C++ class that directly owns dynamic memory, the lecture highlights three coordinated operations: a destructor, a copy constructor, and an overloaded assignment operator. This is commonly called the Rule of Three.

Maya

Could you give me a mental picture of the difference?

Carlos

Imagine two students receive the same locker key. That resembles a shallow copy: both keys lead to one locker, so clearing it through one key affects what the other student sees. A deep copy is a second locker containing duplicated materials. The lockers can then change independently. The analogy is imperfect, but it captures why copying an address is not the same as copying the owned data.

Maya

And the destructor runs automatically when an object leaves its scope?

Carlos

Yes. Its name begins with a tilde, and it releases resources owned by the object. In modern C++, standard containers and smart pointers are usually safer than managing raw arrays manually, but understanding the mechanism explains why ownership and copying matter.

Carlos

Now let’s express the same ideas in Python. Python is a multi-paradigm language, and its object model is pervasive: numbers, strings, functions, classes, and even types themselves are objects. The built-in type function lets us ask what type an object has.

Maya

The syntax is much shorter, and indentation defines the class body instead of braces.

Carlos

The class statement creates a class object. Calling Clock creates an instance. Python then invokes the specially named double-underscore init method to initialize that instance. The self parameter refers to the particular object receiving the method call.

Maya

The slides also say that Python executes through an interpreter. Does that mean Python source is never compiled?

Carlos

That statement is a useful first contrast with a traditional C++ workflow, but the complete picture is more nuanced. A common Python implementation, CPython, compiles source into bytecode and then executes that bytecode in a virtual machine. From the programmer’s perspective, the edit-and-run cycle still feels immediate, and many type decisions occur during execution.

Maya

Is double-underscore init exactly the same as a C++ constructor?

Carlos

They serve a similar teaching purpose, but the mechanics differ. In Python, the instance is created before double-underscore init initializes it. In C++, the constructor participates directly in constructing the object. For an introductory comparison, both establish initial state, but they are not implementation-identical.

Maya

C++ has enforced private and public sections. Does Python?

Carlos

Python relies more on conventions and controlled attribute access. A leading underscore signals that an attribute is intended for internal use, while a double leading underscore triggers name mangling. Neither is the same access-control boundary as C++ private. Python programmers often use properties when they need validation while preserving convenient attribute syntax. COP 4020 Programming Languages • Unit 3 Podcast ---

Maya

And when I write self dot hour, that is instance data. What happens if I assign a name directly in the class body?

Carlos

That normally creates a class attribute shared through the class, unless an instance later shadows it with an attribute of the same name. The distinction matters. Per-object state such as a clock’s current hour belongs on self, while a value common to the class may be a class attribute.

Maya

If both languages support classes, what differences should I notice first?

Carlos

C++ is statically typed and gives programmers direct control over value semantics, memory, and object lifetime. Python is dynamically typed, uses automatic memory management, and usually treats variables as names bound to objects. Those choices change the syntax and the mistakes we must anticipate.

Maya

For example, passing a C++ object by value copies it, while passing by reference can avoid that copy.

Carlos

Correct. Adding const to a C++ reference can prevent the receiving function from modifying the object. In Python, function arguments are object references passed by assignment. A function can mutate a mutable object it receives, but rebinding the local parameter does not rebind the caller’s variable.

Maya

Does automatic memory management mean that Python programmers never need to think about object lifetime?

Carlos

No. It means they usually do not release ordinary objects manually. References still affect how long objects remain reachable, and external resources such as files or network connections should be closed promptly, often with a with statement. C++ and Python automate different parts of resource management, but both reward clear ownership.

Maya

The Python slides also show operator overloading. How does that reinforce object-oriented design?

Carlos

A class can define specially named methods so its instances participate in familiar operations. For example, double-underscore sub can define subtraction, and double-underscore str can define a readable string representation.

Maya

C++ can overload operators too, but Python connects them to these special method names.

Carlos

Exactly. In either language, overloading should preserve an operation’s intuitive meaning. Clever syntax is not a substitute for a clear abstraction.

Maya

So the common design is more important than identical syntax: choose the state, define valid operations, protect the object’s rules, and make object behavior predictable.

Carlos

That is the central lesson. Syntax tells us how to declare a class. Object-oriented design asks whether the class represents one responsibility, maintains valid state, and offers a useful interface.

Carlos

Let’s finish with five review questions. Pause after each question if you need more time.

Carlos

Question 1. What is the difference between a class definition and an object?

Maya

A class defines a type or blueprint. An object is a particular instance with its own instance data. COP 4020 Programming Languages • Unit 3 Podcast ---

Carlos

Question 2. Why would a C++ class keep data members private and provide public accessor and mutator methods?

Maya

To encapsulate the representation, validate changes, preserve the object’s rules, and give client code a stable interface.

Carlos

Question 3. Which C++ constructor runs for the declaration Clock labClock open- parenthesis nine comma thirty comma zero close-parenthesis?

Maya

The constructor whose parameter types best match the three arguments, such as Clock with three integer parameters.

Carlos

Question 4. Why is a shallow copy dangerous when a C++ object owns dynamically allocated memory?

Maya

Both objects may hold the same address. A change affects shared data, and destroying one object can leave the other with an invalid pointer or lead to a double deletion.

Carlos

Question 5. In Python, what roles do self and double-underscore init play?

Maya

Self refers to the current instance. Double-underscore init initializes that instance after it is created.

Carlos

Excellent. If any answer felt uncertain, revisit the class, constructor, and copying examples in the slides and explain them aloud in your own words.

Maya

And try implementing the same small class in C++ and Python. The contrast makes each language’s choices easier to see.

Carlos

That is all for this episode. Thanks for listening to the COP 4020 course podcast. We’ll continue connecting language design to the code we write. COP 4020 Programming Languages • Unit 3 Podcast