Better Programming

Advice for programmers.

Follow publication

Member-only story

Passing Any Type in C++ Like in Python to Simplify Our Code

Debby Nirwan
Better Programming
Published in
7 min readNov 8, 2021

Photo by James Harrison on Unsplash

We first discuss why we need to use Any Type, with examples, followed by how it is implemented using the Type Erasure technique, and finally how it allocates memory to see whether it fits our needs for writing our applications in C++.

Passing Any Type — Why we need it

Dynamically Typed Language

In a dynamically typed programming language like Python, we can pass any type to a function and does check at runtime whether it has the attribute that the function needs or not. For example, the function has a parameter called input.

If we pass a wrong parameter type, for instance, an int, function(3), an exception AttributeError will be raised.

AttributeError: 'int' object has no attribute 'x'

When we pass a type that has an ‘x’ attribute, our function is executed successfully. The same goes to methods, if the method with the same name exists, it will be executed, otherwise an exception is raised.

Statically Typed Language

In a statically typed programming language like C++, we strictly need a type for our parameter. Unlike Python, type checking is performed at compile-time, that’s why we need to know the type.

If we pass a wrong parameter type, for instance, an int, function(3), we’ll get the following compile…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Debby Nirwan
Debby Nirwan

Written by Debby Nirwan

Software Engineering Manager who loves reading, writing, and coding.

Responses (2)

Write a response

Your original design is poor which is why you need to add specific methods for Feed. There should be another class, Food. The objects are the types of food an Animal eats. The constructor for the Animal should accept an instance of Food. Then the…

1