Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

C++ What is the most astounding C++ syntax construct?

C++ is a great language and for me personal the greatest programming language so far.

But there are also constructs possible which may look strange or really complicated.

Do you know some?

I wanna share a strange looking but sometimes very useful example:
C++:
// [...] some missing code here to focus on the important part ...
// a construtcor of some class 'Constructor' (havig some structs/classes X, Y, Z as well)
explicit Constructor( X x, Y y, Z z )
try : mMember1( x )         // A functional try block around the member initilizer list
    , mMember12( y, z )
{
} catch( ... ) {
}
// [...] some more code here ...

Ever seen a such a try-catch block?
If this is new for you: This is a Functional Try Block.
This is useful if in the middle of the member initialization an exception is thrown and the half created class instance need to do some clean up. There is one special behavior in this construct. Do you know which?

The catch block will always re-throw the exception automatically because the class instance was not finally created and stays broken.

One complete example:
C++:
class Foo
{
    std::string mStr;
public:
    // Constructor
    explicit Foo( std::string const & s, size_t pos )
    // # 4: Function try block. The try block includes the initializer list!
    try : mStr( s, pos )
    {
        puts( "Foo constructor - normal block." );
    } catch( ... ) {
        // here can only cleanup already initialized/allocated stuff, which must be clean up manually.
        // Constructed members are destructed already.
        // the class instance itself stays broken. this catch block will auto re-throw the exception always!
        puts( "Foo constructor - catch block!." );
    }
};
 
try {
    std::string s = "test";
    Foo foo1( s, 2 );  // not throw
    Foo foo2( s, 10 ); // will throw std::out_of_range
} catch( ... ) {
}

This example is from my last article of my blog with the title
TOP 5 most astounding C++20 syntax.
You will find 4 other examples there including a godbolt link for try all the code by your self.
https://tea-age.solutions/2022/12/16/top-5-most-astounding-cpp20-syntax/

Do you know other awesome syntax constructs?

Cheers and happy Coding!
 
Thanks for reminding me why I hate C++ 😁
IMHO the really awesome constructs are those which, despite being non-trivial, you can look at and actually understand at a glance.
haha, understand what you are meaning....
The thing with C++ is the higher learning curve compared to other languages, BUT after you are into it, you will love it. 😉
The good point is, that C++ does not force you to use any possible construct. You can use it in that way, which you prefer.
But on the other hand it offers you techniques like a Swiss Army Knife. Everything there if you need it....

I totally agree with your last point. Maybe I can create a future blog post about it. I think such constructs exists as well. 🙂
 
Python:
class Foo:
    def __init__(self, s: str, pos: int):
        try:
            self.mStr = s[pos:]
            print("Foo constructor - normal block.")
        except Exception:
            print("Foo constructor - catch block!")

try:
    s = "test"
    foo1 = Foo(s, 2)  # not throw
    foo2 = Foo(s, 10) # will throw IndexError
except Exception:
    pass
lot more simple in python 🍺
 
that is how you write a constructor in python 🫠
No, Python does not have constructors. It is an init function, or more precise a factory function taking the reference of the object to be created as first argument. It is acting as a replacement for a constructor, yes.
Same in Rust. It does not have constructors but you can provide arbitrary factory functions.
 
From geeksforgeeks

Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors.

Constructor does not have a return value, hence they do not have a return type.


The prototype of Constructors is as follows:

<class-name> (list-of-parameters);
Constructors can be defined inside or outside the class declaration:-


Prerequisites: Object-Oriented Programming in Python, Object-Oriented Programming in Python | Set 2
Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. In Python the __init__() method is called the constructor and is always called when an object is created.
Syntax of constructor declaration :

def __init__(self):
# body of the constructor
Types of constructors :


  • default constructor: The default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.
  • parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.
 
Ok, I checked Python in more detail.
Since you can write
instance = SomeClass( 123 )
and this will call the __init__ function in SomeClass automatically, I agree also that this is a constructor in Python.

But the overall topic is C++ here ... 😉
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom