Question about New syntax of C++

  • C/C++
  • Thread starter yungman
  • Start date
  • Tags
    C++
In summary: Index too large: "+ to_string(index)};//No idea what is this return elements[index]; }/*Written in old syntax: T& operator[](int index) const { try { if(index>=size)throw 0; return elements[index]; }
  • #1
yungman
5,755
293
Hi
I have been literally studying back class overloading in the new C++ syntax( at least that's what I call). This is on class template that is very much like class. I want to verify whether my translation is correct or not. In the program, I have the constructor and operator[] with throw catch written in new form according to the Ivor book. Then following those with my translation to the old style syntax. Can anyone check whether I am right?

I am quite sure the constructor is correct, it's the try throw catch part that I have question in line 24, I don't understand + to_string(index). I just use my best guess in my translation to the old syntax.
C++:
//Ivor page 617
#include<iostream>
using namespace std;
template<typename T> class Array
{
private: T* elements; size_t size;
public:
    explicit Array<T>(size_t aSize) //Constructor
    : elements{ new T[aSize] }, size{ aSize }{}
    Array<T>(const Array<T>& array) : Array{ array.size }
    {for (size_t i{}; i < size; ++i)elements[i] = array.elements[i];}
/*Constructor written in old syntax:
    explicit Array<T>(int aSize)
    {
       element=new T[aSize];size=aSize;
       for(int i=0;i<size;I++)elements[i]=array.elements[i];
    }*/

    ~Array<T>() { delete[] elements; }

    T& operator[](size_t index) const
    {
        if (index >= size)
          throw out_of_range{" Index too large: "+ to_string(index)};//No idea what is this
        return elements[index];
    }
/*Written in old syntax:
    T& operator[](int index) const
    {
      try
        {
         if(index>=size)throw 0;
         return elements[index];
        }
      catch(int i){ cout << " Index too large.\n\n";}
    }*/

    Array<T>& operator = (const Array<T>& rhs)
    {
        if (&rhs != this)
        {    delete[] elements;//why have this?
            size = rhs.size;
            elements = new T[size];
            for (size_t i{}; i < size; ++i)
            {elements[i] = rhs.elements[i];}
        }
        return *this;
    }
    size_t getSize() const { return size; }
};

My other question, which is more important:
If those are "new" and "better" syntax is supposed to simplify the program, how is it better? From here, I have been told to make the program easier to read and understand by other people, that I even have to use names that are easier to understand...In what world the new syntax are easier to understand? In what world the new syntax are shorter and simpler?

At least the old way of writing is more English, that it's easier to understand.

I know I have NO CHOICE but to stop and relearn this, it's like take it or leave it. I just wonder what you guys think.

Thanks
 
Technology news on Phys.org
  • #2
yungman said:
Hi
I have been literally studying back class overloading in the new C++ syntax( at least that's what I call). This is on class template that is very much like class. I want to verify whether my translation is correct or not. In the program, I have the constructor and operator[] with throw catch written in new form according to the Ivor book. Then following those with my translation to the old style syntax. Can anyone check whether I am right?

I am quite sure the constructor is correct, it's the try throw catch part that I have question in line 24, I don't understand + to_string(index). I just use my best guess in my translation to the old syntax.
C++:
//Ivor page 617
#include<iostream>
using namespace std;
template<typename T> class Array
{
private: T* elements; size_t size;
public:
    explicit Array<T>(size_t aSize) //Constructor
    : elements{ new T[aSize] }, size{ aSize }{}
    Array<T>(const Array<T>& array) : Array{ array.size }
    {for (size_t i{}; i < size; ++i)elements[i] = array.elements[i];}
/*Constructor written in old syntax:
    explicit Array<T>(int aSize)
    {
       element=new T[aSize];size=aSize;
       for(int i=0;i<size;I++)elements[i]=array.elements[i];
    }*/

    ~Array<T>() { delete[] elements; }

    T& operator[](size_t index) const
    {
        if (index >= size)
          throw out_of_range{" Index too large: "+ to_string(index)};//No idea what is this
        return elements[index];
    }
/*Written in old syntax:
    T& operator[](int index) const
    {
      try
        {
         if(index>=size)throw 0;
         return elements[index];
        }
      catch(int i){ cout << " Index too large.\n\n";}
    }*/

    Array<T>& operator = (const Array<T>& rhs)
    {
        if (&rhs != this)
        {    delete[] elements;//why have this?
            size = rhs.size;
            elements = new T[size];
            for (size_t i{}; i < size; ++i)
            {elements[i] = rhs.elements[i];}
        }
        return *this;
    }
    size_t getSize() const { return size; }
};

My other question, which is more important:
If those are "new" and "better" syntax is supposed to simplify the program, how is it better? From here, I have been told to make the program easier to read and understand by other people, that I even have to use names that are easier to understand...In what world the new syntax are easier to understand? In what world the new syntax are shorter and simpler?

At least the old way of writing is more English, that it's easier to understand.

I know I have NO CHOICE but to stop and relearn this, it's like take it or leave it. I just wonder what you guys think.

Thanks
The first one, the "old syntax" looks wrong. There is no "array" to copy to. If you correct it, it looks like this,

Code:
explicit Array<T>(int aSize) {
    element=new T[aSize];
    size=aSize;
}

That is just initializing the member variables element and size. The new version is using the constructor member initializer list, which allows you to initialize member variables at the same time they are created. It is supporting this behavior for example, A a(3); as opposed to getting this behavior: A a(); a.set( 3 );

This is because the member variables are already created by time the constructor body executes, while the member initializer list happens before at the time the variables are first created. So if you don't use the initializer list, the members are constructed first with the default constructor (if they are objects). But maybe you want to initialize them using a particular non-default constructor?

https://www.learncpp.com/cpp-tutorial/constructor-member-initializer-lists/

The second block of new code is just different. It's not catching the exception in the function but instead relying on the user to handle the exception if they want to. Note that in your version, the program keeps going even if you get an exception. But with the new version, unless the user writes their own code to handle it, it will be uncaught and the program with just exit.

In the third one, it deletes elements because the two arrays might be different sizes. So it deletes the existing one, which may be different size, and allocates the correct amount of memory.

"index = " + to_string(index), converts the index number to a string value, then the resulting string calls its operator + to concatenate the adjacent string literal to it. The result of the expression is then a string.

In all of the cases, you can't really call it new syntax. They are not doing the same things.
 
Last edited:
  • Like
Likes yungman
  • #3
Jarvis323 said:
The first one, the "old syntax" looks wrong. There is no "array" to copy to. If you correct it, it looks like this,

Code:
explicit Array<T>(int aSize) {
    element=new T[aSize];
    size=aSize;
}

That is just initializing the member variables element and size. The new version is using the constructor member initializer list, which allows you to initialize member variables at the same time they are created. It is supporting this behavior for example, A a(3); as opposed to getting this behavior: A a(); a.set( 3 );
Hi Javis323

Thanks for answering.

My bad, I missed the copy constructor. This is the revised first part:
C++:
    explicit Array<T>(size_t aSize) //Constructor
    : elements{ new T[aSize] }, size{ aSize }{}
/*Constructor same as:
    explicit Array<T>(int aSize)
    {
       int size = array.size;
       element=new T[aSize];size=aSize;
    }*/
    Array<T>(const Array<T>& array) : Array{ array.size }
    {for (size_t i{}; i < size; ++i)elements[i] = array.elements[i];}
/*Copy constructor
    Array<T>(const Array<T>& array)
    {
       int size = array.size;
       for (int i{}; i < size; +i++)elements[i] = array.elements[i];
    }*/
Still the old syntax is clearer. also, if the program runs line by line, the order is wrong in the new syntax. Line 10 should it be
C++:
  size{ aSize }{}, elements{ new T[aSize] }
to set size = aSize first before copying?

What is the reason using size_t instead of int?

I need to read the second part and come back later.

Thanks
 
Last edited:
  • #4
yungman said:
What is line 4?

elements is the member variable which is storing the raw data for the Array. Line 4 is copying the elements from the argument, array.elements, into the newly constructed object's elements.

yungman said:
What is the reason using size_t instead of int?

An int is at least 16 bits, but usually 32 bits (depending on the system). If it's 32 bits, then it can store integers in the range, -2,147,483,648 to 2,147,483,647. So using an int to store the size of something will fail if the size is larger than 2,147,483,647. size_t is an unsigned integer type that is guaranteed large enough to represent the size of any type. When you use the sizeof function, it returns a size_t, and when you use vector::size() it returns size_t.
 
  • Like
Likes jim mcnamara and yungman
  • #5
yungman said:
Still the old syntax is clearer. also, if the program runs line by line, the order is wrong in the new syntax. Line 10 should it be
C++:
  size{ aSize }{}, elements{ new T[aSize] }
to set size = aSize first before copying?
Thanks
In this case, it doesn't matter which order. They don't depend on each other, only on the argument aSize. But anyways, for the member initializer list, the initialization order isn't actually how it appears in the list. The order they are constructed in is the order they appear in the class definition.

For example,

C:
#include <iostream>
using namespace std;

struct A {
    A() { cout << "A"; }
};

struct B {
    B() { cout << "B"; }
};

struct T {
    A a;
    B b;
    T() : b(), a() { }
};

int main() {
    T t;
}

In this example, a() happens first, as you can see from the output.
 
Last edited:
  • Like
Likes yungman
  • #6
Also, check this example. Because int tk; is after A a;, A b; in the definition of T, A(tk) and B(tk) are done before tk( k ), and so they are initizlized with the uninitialized tk that has a garbage value. So if you do make one constructor depend on another like this in your list, make sure the order they appear in the definition is correct.

Compilers will warn you if the order they appear in the class definition is different than the order in the member initialization list to help prevent you from making this type of mistake.

C:
#include <iostream>
using namespace std;

struct A {
    int ka;
    A( int k ) { ka = k; cout << "A: " << ka << endl; }
};

struct B {
   int kb;
    B( int k ) { kb = k; cout << "B: " << kb << endl; }
};

struct T {
    A a;
    B b;
    int tk;
    T( int k ) : tk( k ), b( tk ), a( tk ) { }
};

int main() {
    T t( 3 );
}
 
  • #7
Jarvis323 said:
Also, check this example. Because int tk; is after A a;, A b; in the definition of T, A(tk) and B(tk) are done before tk( k ), and so they are initizlized with the uninitialized tk that has a garbage value. So if you do make one constructor depend on another like this in your list, make sure the order they appear in the definition is correct.

Compilers will warn you if the order they appear in the class definition is different than the order in the member initialization list to help prevent you from making this type of mistake.

C:
#include <iostream>
using namespace std;

struct A {
    int ka;
    A( int k ) { ka = k; cout << "A: " << ka << endl; }
};

struct B {
   int kb;
    B( int k ) { kb = k; cout << "B: " << kb << endl; }
};

struct T {
    A a;
    B b;
    int tk;
    T( int k ) : tk( k ), b( tk ), a( tk ) { }
};

int main() {
    T t( 3 );
}
Thanks Javis323

I ran this program, ka and kb are all garbage. I stepped through the program, tk in struct T never got passed into a or b even it stepped to struct A and B. Why?

thanks
 
  • #8
I have not studied struct that acts like class. I want to verify some stuffs here:
C++:
#include <iostream>
using namespace std;

struct A {
    int ka;
    A( int k ) { ka = k; cout << "A: " << ka << endl; }//Is this like a constructor in class?
};

struct B {
   int kb;
    B( int k ) { kb = k; cout << "B: " << kb << endl; }//Is this like a constructor in class?
};

struct T {
    A a;
    B b;
    int tk;
    T( int k ) : tk( k ), b( tk ), a( tk ) { }
/*Is line 18  constructor for T like
   T(int k)
   { tk=k;
    b(tk);// instantiate an object of B with kb=tk
    a(tk);//instantiate an object of A with ka=tk
    }*/
};

int main() {
    T t( 3 );
}

The question is in line 19 to 24.

If I am right, I don't understand why I get garbage in k in a and b. I stepped through the whole program, it goes to the constructors of a and b with the correct value of 3. The parameter just did NOT pass over to create a and b.

Thanks
 
  • #9
yungman said:
I have not studied struct that acts like class.
But you've been told that the only difference between C++ structs and classes is the default access privileges -- in a struct, all members are public by default; in a class, all members are private by default. Both structs and classes can have constructors, member functions, overloaded operators, etc.
 
  • Like
Likes Vanadium 50
  • #10
Mark44 said:
But you've been told that the only difference between C++ structs and classes is the default access privileges -- in a struct, all members are public by default; in a class, all members are private by default. Both structs and classes can have constructors, member functions, overloaded operators, etc.
Yeh, but Geddis say nothing about it, I did not realize struct can actually looks like class with constructor and all that. The more I study now, the more I feel Geddis is NOT a good book, not that because my book is old, it skips a lot of stuffs.

If I just follow Gaddis chapter 16 on exception, function templates and class templates, I would have( I have finished) a month ago. I am using Ivor book and I actually started deleting the notes written on Gaddis. I learn NOTHING on struct in Gaddis book except it can create objects with multiple variables inside the struct object. I learn VERY LITTLE in templates with Gaddis. It's like starting over with Ivor book. Ivor is a lot more detail and divide into two chapters. My issue is the new syntax I am struggling with, the template actually is not that hard at all, just like reviewing the function and class again.

I think after this chapter, I am going to start with the graphics books on C++ by John Horton and learn the new stuffs while I go through the book from the beginning. Hopefully Horton covers the new stuffs.

Still come back to the question. You guys stressed so much to make the program easier to read even if I have to make the name longer, separate into smaller lines and all. In what world the new syntax is easier to read? So far, it's not exactly making the statement shorter. It definitely make it much harder to read.

I read some Java and python programs, I basically understand what they are doing even though I don't know the exact syntax. Unless Java and python are going the same direction. C++ would be impossible to read if it is written in the new syntax. That is a sure way to self shrinking it's own market share as people just afraid to even go there. Imagine I have a hell of the time understanding the new syntax, how are the people that don't know anything in C++ going to feel?

Let's compare
C++:
int a, b;

if(a>b) return a;
else return b.

a > b ? a :b;
Which one is easier to read? If I go into if-else if-else. It really looks messy in the new syntax.
 
Last edited:
  • #11
yungman said:
Yeh, but Geddis say nothing about it

False.

Gaddis (Section 13.2 p 718) said:
A class is similar to a structure...Unlike structures, the members of a class are private by default.
 
  • #12
yungman said:
Yeh, but Geddis say nothing about it, I did not realize struct can actually looks like class with constructor and all that. The more I study now, the more I feel Geddis is NOT a good book, not that because my book is old, it skips a lot of stuffs.
A question an author must face is should I go for depth or for breadth? You can't expect a single book to cover every feature in detail.
yungman said:
If I just follow Gaddis chapter 16 on exception, function templates and class templates, I would have( I have finished) a month ago. I am using Ivor book and I actually started deleting the notes written on Gaddis.
I learn NOTHING on struct in Gaddis book except it can create objects with multiple variables inside the struct object. I learn VERY LITTLE in templates with Gaddis. It's like starting over with Ivor book. Ivor is a lot more detail and divide into two chapters. My issue is the new syntax I am struggling with, the template actually is not that hard at all, just like reviewing the function and class again.

I think after this chapter, I am going to start with the graphics books on C++ by John Horton and learn the new stuffs while I go through the book from the beginning. Hopefully Horton covers the new stuffs.

Still come back to the question. You guys stressed so much to make the program easier to read even if I have to make the name longer, separate into smaller lines and all. In what world the new syntax is easier to read? So far, it's not exactly making the statement shorter. It definitely make it much harder to read.
The goal is to make a program more understandable, part of which is to use variable names whose purposes can be deduced from their names. Cramming two or three or more statements on a single line makes programs less understandable, as it's easy to miss something with so many actions occurring in one place.

Which "new syntax" are you talking about? If it's the example below, with the conditional operator -- ?: -- that's far from being new. The conditional (or ternary) operator has been in C from very early on, and was carried over to C++. It's also present in the same form in Java, and in slightly different form in Python.

If that's not what you mean by "new syntax" please be more specific about what you mean.
yungman said:
I read some Java and python programs, I basically understand what they are doing even though I don't know the exact syntax. Unless Java and python are going the same direction. C++ would be impossible to read if it is written in the new syntax. That is a sure way to self shrinking it's own market share as people just afraid to even go there. Imagine I have a hell of the time understanding the new syntax, how are the people that don't know anything in C++ going to feel?

Let's compare
C++:
int a, b;

if(a>b) return a;
else return b.

a > b ? a :b;
Which one is easier to read? If I go into if-else if-else. It really looks messy in the new syntax.
This is not "new syntax". This is a standard idiom in C, C++, and Java, and many other languages.
 
  • #13
Vanadium 50 said:
False.
What do you mean by WRONG. I studied the book, it never talked about constructor, copy constructor and all that. READ THE BOOK.
 
  • #14
Mark44 said:
A question an author must face is should I go for depth or for breadth? You can't expect a single book to cover every feature in detail.
The goal is to make a program more understandable, part of which is to use variable names whose purposes can be deduced from their names. Cramming two or three or more statements on a single line makes programs less understandable, as it's easy to miss something with so many actions occurring in one place.

Which "new syntax" are you talking about? If it's the example below, with the conditional operator -- ?: -- that's far from being new. The conditional (or ternary) operator has been in C from very early on, and was carried over to C++. It's also present in the same form in Java, and in slightly different form in Python.

If that's not what you mean by "new syntax" please be more specific about what you mean.
This is not "new syntax". This is a standard idiom in C, C++, and Java, and many other languages.
Then Gaddis book that I have never cover this.

You mean Java and Python have this also? Anyway, I know I have to learn this. I should have use the Ivor book from day one even though it's harder.

I am going to study John Horton from the beginning, hopefully it will cover all these. At the mean time, I am struggling to finish the chapter on templates and I'll be all good. Just want to finish the chapter, just bear with me. Only like 20 more pages to go with those syntax. then i can throw the Gaddis book away and start fresh.
 
  • #15
yungman said:
READ THE BOOK.

You might take your own advice.

Note that I pointed out exactly where in Gaddis this was. Everybody can see it for themselves.

yungman said:
t never talked about constructor, copy constructor and all that.

That's moving the goalposts, but do you really want to say that Gaddis doesn't talk about constructors? Really? You might take a look at sections 13.7 and 14.4 before going any further down that particular road.
 
  • #16
Vanadium 50 said:
You might take your own advice.

Note that I pointed out exactly where in Gaddis this was. Everybody can see it for themselves.
That's moving the goalposts, but do you really want to say that Gaddis doesn't talk about constructors? Really? You might take a look at sections 13.7 and 14.4 before going any further down that particular road.
You read part of my post. I SAID GADDIS NEVER TALK ABOUT CONSTRUCTOR, COPY CONSTRUCTOR AND ALL THAT IS CHAPTER 11 ON STRUCTURE.

READ BEFORE YOU MAKING PUT DOWN REMARKS. I WORK THROUGH EACH AND EVERY SINGLE PROGRAM IN CHAPTER 11.
 
  • #17
yungman said:
You read part of my post. I SAID GADDIS NEVER TALK ABOUT CONSTRUCTOR, COPY CONSTRUCTOR AND ALL THAT IS CHAPTER 11 ON STRUCTURE.

READ BEFORE YOU MAKING PUT DOWN REMARKS. I WORK THROUGH EACH AND EVERY SINGLE PROGRAM IN CHAPTER 11.
I feel like you should be easier on your judgement. I remember distinctly that Mark had already told you that structs are the same as classes except that by default they have pubic access to members. If you've forgotten that, then how can you be sure that you haven't forgotten what you've read in a book?

And then it does look like Gaddis also wrote that structs are the same as classes except with public access by default. That is literally the only difference, so why should any more be said about it? If you are complaining that Gaddis didn't repeat it enough times, then how can you also complain if Gaddis left something out, without expecting the book to be many thousands of pages long? And people aside from yourself might be annoyed if it is unnecessarily long.

We also warned you a whole lot that C++ is a lot to learn and one of the most complicated languages. You chose to learn it anyway, which is great, but I don't understand why you want to complain about it. It is like hiking Mount Everest and being upset that it's cold up there. And where you're at now is really only the base camp.
 
Last edited:
  • Like
Likes phinds, Vanadium 50 and pbuk
  • #18
Jarvis323 said:
I feel like you should be easier on your judgement. I remember distinctly that Mark had already told you that structs are the same as classes except that by default they have pubic access to members. If you've forgotten that, then how can you be sure that you haven't forgotten what you've read in a book?

And then it does look like Gaddis also wrote that structs are the same as classes except with public access by default. That is literally the only difference, so why should any more be said about it? If you are complaining that Gaddis didn't repeat it enough times, then how can you also complain if Gaddis left something out, without expecting the book to be many thousands of pages long? And people aside from yourself might be annoyed if it is unnecessarily long.

We also warned you a whole lot that C++ is a lot to learn and one of the most complicated languages. You chose to learn it anyway, which is great, but I don't understand why you want to complain about it. It is like hiking Mount Everest and being upset that it's cold up there. And where you're at now is really only the base camp.
I tried to send you a private message and I cannot find the way here. I am not saying against you or any others. I was specifically talking about Gaddis chapter 11 on structure that it has nothing about constructor and copy constructor.

I just went through the Gaddis 6th edition chapter 11 again, there is no constructor, copy constructor or any of the operator, overload and all that. I worked on every single program in that chapter, I did not forget. There is one mention on member function, but not even in the program.

Chapter 13 in class is the first time Gaddis mention about constructor, copy constructor. Chapter is the first chapter that have overloading.

If I can find out how to PM you, I will explain a lot more why I wrote what I wrote.

Thanks
 
  • #19
yungman said:
I tried to send you a private message and I cannot find the way here. I am not saying against you or any others. I was specifically talking about Gaddis chapter 11 on structure that it has nothing about constructor and copy constructor.

I just went through the Gaddis 6th edition chapter 11 again, there is no constructor, copy constructor or any of the operator, overload and all that. I worked on every single program in that chapter, I did not forget. There is one mention on member function, but not even in the program.

Chapter 13 in class is the first time Gaddis mention about constructor, copy constructor. Chapter is the first chapter that have overloading.

If I can find out how to PM you, I will explain a lot more why I wrote what I wrote.

Thanks
For some reason, when I signed up, I went through all of the settings, and chose to disable private messaging. There wasn't any big reason, I just went through all of the options quickly and chose no private messaging. I guess I didn't see a reason to get involved in private conversations. No need to explain anything to me privately or anything. It's a public forum, and I'm not the only reader. I feel like it's better to just explain whatever you want to explain openly.
 
  • #20
Jarvis323 said:
I remember distinctly that Mark had already told you that structs are the same as classes except that by default they have pubic access to members.

He's been told new fewer than five times by no fewer than three members. Mark holds the record with three.
 
  • #21
Jarvis323 said:
For some reason, when I signed up, I went through all of the settings, and chose to disable private messaging. There wasn't any big reason, I just went through all of the options quickly and chose no private messaging. I guess I didn't see a reason to get involved in private conversations. No need to explain anything to me privately or anything. It's a public forum, and I'm not the only reader. I feel like it's better to just explain whatever you want to explain openly.
OK, my beef is with ONE particular person. This is nothing new. he did NOT read the post, he accused me wrongly, he almost never help, only insult. If it is not because of the respect towards to this forum, I have a lot more colorful words to say to his face. This is ONLY towards one person here only. I apologize if I offend anyone else as it's not meant to be for others.

This is an education forum, how can this forum allow someone like this? If one doesn't like to help or doesn't like a person, put the person on ignore, don't reply. GET A LIFE instead of wasting time looking back on pass posts to count who say what and how many times.

I think I am very grateful and polite to anyone that helps me, it's not as if I argue with anyone else.
 
Last edited:
  • #22
Jarvis323 said:
Also, check this example. Because int tk; is after A a;, A b; in the definition of T, A(tk) and B(tk) are done before tk( k ), and so they are initizlized with the uninitialized tk that has a garbage value. So if you do make one constructor depend on another like this in your list, make sure the order they appear in the definition is correct.

Compilers will warn you if the order they appear in the class definition is different than the order in the member initialization list to help prevent you from making this type of mistake.

C:
#include <iostream>
using namespace std;

struct A {
    int ka;
    A( int k ) { ka = k; cout << "A: " << ka << endl; }
};

struct B {
   int kb;
    B( int k ) { kb = k; cout << "B: " << kb << endl; }
};

struct T {
    A a;
    B b;
    int tk;
    T( int k ) : tk( k ), b( tk ), a( tk ) { }
};

int main() {
    T t( 3 );
}
I have been working on this program. I really don't understand your definition of struct T. What you have does not work, I have to move int tk from line 17 to line 14 to make it works. I made comment on those lines. I have no idea how this new syntax work at all.
This is what I have using the old syntax, I put the old syntax in comment between line 21 to line 26. It's easy to make this work. I just don't know how to read the way you write. Is there a name for the new syntax? Is there anything article that talk about this kind of syntax? Or I just have to go through a new book quickly to learn all these?
C++:
#include <iostream>
using namespace std;
struct A1 {
    int ka;
    A1( int k)
    { ka = k; cout << "A1: " << ka << endl; }
};
struct B1 {
   int kb;
    B1( int k )
    { kb = k; cout << "B1: " << kb << endl; }
};
struct T1 {
    int tk;//works when put tk in front of declaration of a1 and b1
    A1 a1;
    B1 b1;
//  int tk;//original program has it here, it would NOT work.
    T1( int k ) : tk( k ),
        b1( tk ),
        a1( tk ) { }
   /* T1(int k)//This is the old way, it's easy and it works!
    {
        tk = k;
        B1 b1(tk);
        A1 a1(tk);
    }*/
};

int main()
{
    T1 t1( 3 );
}

This is EASY program if only I know how to read this new syntax. Just like template, it's not that hard, just the book that I have to use now is using this kind of syntax and I am desperately trying to get through this chapter so I can start all over again with the John Horton book on graphics with C++. Horton's book is new, hopefully I can learn all these while I go through the book from chapter 1 learning graphics programming and learn the new syntax along. I just want to finish this last 15 to 20 pages on template and I can burn the Gaddis book for good.

thanks
 
  • #23
We've been around this block before.

You ask a question.
People tell you what you need to do.
You don't do it.
It doesn't work out for you.
You blame them for being unhelpful.
Repeat.

Do you really think this is the path forward? You've gotten thousands of messages worth of advice. Doesn't it make sense to take it? Claiming you've never been told something when anybody can tell with the search function you've been toild multiple times - like five in this case - hoiw does it help?
 
  • #24
yungman said:
C++:
   /* T1(int k)//This is the old way, it's easy and it works!
    {
        tk = k;
        B1 b1(tk);
        A1 a1(tk);
    }*/
Is it the old way though? And does it work?
 
  • #25
Jarvis323 said:
Is it the old way though? And does it work?
Yes, After I change one line of yours and the old way both work.

One think, I decided to stop the template as I am not learning the template anymore, I am struggling with the syntax. I decided to stop and get on with games with C++ with John Horton 2nd edition that was out in 2019. That should be up to date. I thumb through the book, I do NOT see any of those "new syntax"! Big surprise!

Is the new syntax more common? How come the new John Horton doesn't seem to use it. I read through a few pages here and there, I understand what he is writing! Should I keep banging my head on the wall to learn this new syntax?

If it is not, forget it, I understand templates just fine. Horton's book seems to teach C++ at the same time introducing games, it's good for me to revise what I learn from the beginning starting from variables, to condition statements and loops, function, class...

Thanks
 
  • #26
yungman said:
Yes, After I change one line of yours and the old way both work.
I know that my example has that behavior, if you read the post, that was the point.

I'm pointing out now that your way doesn't work in this case, and is impossible to make work. If you understand why, then you'll understand why there is a constructor member initializer list.

The member initializer list isn't new, it's a feature that's been part of C++ all along. It allows you to initialize a member variable when it's created. It's common, and necessary to use in some cases. It's not just a different syntax.
 
  • #27
Jarvis323 said:
I know that my example has that behavior, if you read the post, that was the point.

I'm pointing out now that your way doesn't work in this case, and is impossible to make work. If you understand why, then you'll understand why there is a constructor member initializer list.

The member initializer list isn't new, it's a feature that's been part of C++ all along. It allows you to initialize a member variable when it's created. It's common, and necessary to use in some cases. It's not just a different syntax.
I read your post, honestly, I don't understand at all why moving int tk up make a difference, why the k=3 doesn't pass to the A and B constructor. Why the order of what you wrote is not important. I don't understand why it doesn't give me an error when you write A a; B b; because the constructor needs to have one parameter, you need to write A a(tk); I am just totally lost.

I just never learn that before and hope to find a book to learn it eventually. I don't think it is fair to have you guide me through step by step how to understand it, I need a book or some material.

But as I said, Horton book doesn't seems to use the new syntax at all. That's why I ask whether it is important to learn this.

I understand what I wrote the old way.
 
  • #28
yungman said:
I read your post, honestly, I don't understand at all why moving int tk up make a difference, why the k=3 doesn't pass to the A and B constructor. Why the order of what you wrote is not important. I don't understand why it doesn't give me an error when you write A a; B b; because the constructor needs to have one parameter, you need to write A a(tk); I am just totally lost.

When an instance of a class/struct is created, each of its member variables are created in the order they appear in the definition. When an object is created, its constructor is called.

If you just use your old syntax, the default constructor with no arguments is used. If you want to use a constructor with arguments you have to use the member initializer list to say which one and pass the arguments. But that doesn't change the order they are called. It's still the order they appear in the definition.

Your way won't work in this example because A,B don't have a default constructor (because making custom one with arguments gets rid if the default one). So instances of A and B can only be created with the constructor with an argument, which can only be accomplished in T using the member initializer list.

A a(tk) and B b(tk) get garbage values because in the definition of T, tk appears last, so it's created last. So the constructors for a, and b are called before tk has been given a value. I put tk(k) first in the member initializer list to demonstrate that the order the members are created isn't changed by the order in the initializer list, it's still just the order they are defined, and so tk is still initialized last.

I know it is a little complicated. It's fine if you want to avoid using it, and other more advanced parts of the language. C++ gets a lot more complicated than you can imagine if you try to learn everything.
 
Last edited:
  • Informative
Likes Mark44
  • #29
Thanks so much Jarvis323. I did NOT know if I write the T1(int k) constructor, then I cannot assume there will be a default constructor. I was wondering why I cannot put A1 a1; B1 b1;. That answer my question. My old syntax program works, I might have typos, this is what I have.
C++:
//Javis323 example using new syntax
#include <iostream>
using namespace std;
struct A1
{
    int ka;
    A1( int k)
    { ka = k; cout << "A1: " << ka << endl; }
};
struct B1
{
   int kb;
    B1( int k )
    { kb = k; cout << "B1: " << kb << endl; }
};
struct T1
{
    int tk;
    T1(int k)
    {
        tk = k;
        B1 b1(tk);
        A1 a1(tk);
    }
};

int main()
{
    T1 t1( 3 );
}
I made your program work, but I don't understand why the compiler won't flag error when you have A1 a1; B1 b1; with NO default constructor. I understand int tk; has to come first, but in your A1 a1;, you are not looking for any parameter, why does that matter?
C++:
#include <iostream>
using namespace std;
struct A1 {
    int ka;
    A1( int k)
    { ka = k; cout << "A1: " << ka << endl; }
};
struct B1 {
   int kb;
    B1( int k )
    { kb = k; cout << "B1: " << kb << endl; }
};
struct T1
{
    int tk;//Have to put it here to work
    A1 a1;//I have no default constructor, why this not flagging error?
    B1 b1;//I have no default constructor, why this not flagging error?
    //int tk; This will not work putting here.
    T1( int k ) : tk( k ),
        b1( tk ),
        a1( tk ) { }
};
int main()
{
    T1 t1( 3 );
}

I put the question in the comments in the program.

I am already spending a little time on the Horton game with C++ book. I am loosing interest with this new syntax or whatever you call it. I thought all new books are using this kind of syntax that I MUST learn. Horton is a new book from 2019, it doesn't use that kind of syntax. Like you said, you can never learn everything about C++ and I don't intend to. I think I did pretty good finishing one book from cover to cover already. The template, exception is not even in the book and I study extra. It's like when is enough is enough? I need to see some result, 7 months of dry study is enough already. You ask why I choose C++? because it's hard! Why people climb Mt Everest? Because it's tall! I did it in my old age instead of staying in my comfort zone and go to the electronics forum and claim I am an expert! Believe me, the last 7 months really build character for me, learning to be humble. People here should try that too, going into something you are actually green and know nothing and start over again. It's a very good experience. It's my way of keeping young just like I still work hard in weight lifting and kickboxing to compare my physical shape with someone in their 30s or 40s.

I have no plan on doing anything with C++, it's just a tall mountain, and I want to climb it! I doubt I will ever finish the Horton book as I am starting to lose interest already. I'll see how far will I go. Electronics is starting to call me again and I found another hobby already.

Thanks
 
Last edited:
  • #30
yungman said:
I made your program work, but I don't understand why the compiler won't flag error when you have A1 a1; B1 b1; with NO default constructor.
C++:
#include <iostream>
using namespace std;
struct A1 {
    int ka;
    A1( int k)
    { ka = k; cout << "A1: " << ka << endl; }
};
struct B1 {
   int kb;
    B1( int k )
    { kb = k; cout << "B1: " << kb << endl; }
};
struct T1
{
    int tk;//Have to put it here to work
    A1 a1;//I have no default constructor, why this not flagging error?
    B1 b1;//I have no default constructor, why this not flagging error?
    //int tk; This will not work putting here.
    T1( int k ) : tk( k ),
        b1( tk ),
        a1( tk ) { }
};
int main()
{
    T1 t1( 3 );
}
I think the reason why it's not an error to omit the default constructors, is that in this program, the compiler never actually looks for a default constructor. The member declarations A1 a1; and B1 b1; by themselves do not invoke any constructors. That happens only when T1's constructor is invoked; that constructor explicitly invokes the non-default constructors A1 (int k) and B1 (int k), so the compiler never needs to look for a default constructor A1 () or B1 ().

Try removing either b1( tk ) or a1( tk ) from the initializer list for T1( int k ) and see what happens. This will force the compiler to look for a default constructor.

Here's a simpler program that illustrates the behavior that you're seeing:

C++:
#include <iostream>
using namespace std;

struct A {
    int ka;
    A( int k ) { ka = k; cout << "A: " << ka << endl; }
};

int main() {
    cout << "I'm not constructing any objects of type A." << endl;
    return 0;
}

This compiles successfully for me. Now, in main(), first add A a; which looks for a default constructor (and edit the output to cout if you like :wink: ). Then change it to A a(3); .
 
Last edited:
  • Like
Likes yungman
  • #31
jtbell said:
I think the reason why it's not an error to omit the default constructors, is that in this program, the compiler never actually looks for a default constructor. The member declarations A1 a1; and B1 b1; by themselves do not invoke any constructors. That happens only when T1's constructor is invoked; that constructor explicitly invokes the non-default constructors A1 (int k) and B1 (int k), so the compiler never needs to look for a default constructor A1 () or B1 ().

Try removing either b1( tk ) or a1( tk ) from the initializer list for T1( int k ) and see what happens. This will force the compiler to look for a default constructor.

Here's a simpler program that illustrates the behavior that you're seeing:

C++:
#include <iostream>
using namespace std;

struct A {
    int ka;
    A( int k ) { ka = k; cout << "A: " << ka << endl; }
};

int main() {
    cout << "I'm not constructing any objects of type A." << endl;
    return 0;
}

This compiles successfully for me. Now, in main(), first add A a; which looks for a default constructor (and edit the output to cout if you like :wink: ). Then change it to A a(3); .
Thanks for the reply.

But it sure gave me a compiler error if I write it in my old way. I have to delete it to make it work.
C++:
#include <iostream>
using namespace std;
struct A1
{
    int ka;
    A1( int k)
    { ka = k; cout << "A1: " << ka << endl; }
};
struct B1
{
   int kb;
    B1( int k )
    { kb = k; cout << "B1: " << kb << endl; }
};
struct T1
{
    int tk;
//I cannot put A1 a1; B1 b1; here unless I write a default constructor.
    T1(int k)
    {
        tk = k;
        B1 b1(tk);
        A1 a1(tk);
    }
};
int main()
{
    T1 t1( 3 );
}

Please read line 18. This is a working program, but if I put A1 a1; B1 b1; in line 18, compiler will give me error unless I actually write in the default constructor.

If you look at the new syntax, compiler does not flag an error. That program does not have a default constructor, It is inconsistent. It's the new syntax that is different.

Thanks
 
  • #32
yungman said:
Thanks for the reply.

But it sure gave me a compiler error if I write it in my old way. I have to delete it to make it work.
C++:
#include <iostream>
using namespace std;
struct A1
{
    int ka;
    A1( int k)
    { ka = k; cout << "A1: " << ka << endl; }
};
struct B1
{
   int kb;
    B1( int k )
    { kb = k; cout << "B1: " << kb << endl; }
};
struct T1
{
    int tk;
//I cannot put A1 a1; B1 b1; here unless I write a default constructor.
    T1(int k)
    {
        tk = k;
        B1 b1(tk);
        A1 a1(tk);
    }
};
int main()
{
    T1 t1( 3 );
}

Please read line 18. This is a working program, but if I put A1 a1; B1 b1; in line 18, compiler will give me error unless I actually write in the default constructor.

If you look at the new syntax, compiler does not flag an error. That program does not have a default constructor, It is inconsistent. It's the new syntax that is different.

Thanks
In this version, a1 and b1 aren't member variables. That's not a working version. a1, b1 aren't part of T anymore. They're local variables inside T's constructor and are gone once T's constructor finishes.
 

FAQ: Question about New syntax of C++

What is the purpose of the new syntax in C++?

The new syntax in C++ was introduced to make the language more efficient and user-friendly. It includes new features such as lambda expressions, range-based for loops, and auto type inference, which help simplify and streamline the coding process.

How does the new syntax affect existing code?

The new syntax may affect existing code if it uses deprecated features or relies on certain language constructs that have been changed or removed. However, most existing code should still be compatible with the new syntax, and any necessary updates can be made with relative ease.

Are there any performance improvements with the new syntax?

While the new syntax does not directly impact performance, it may indirectly improve performance by encouraging developers to write more efficient and optimized code. Additionally, some of the new features, such as move semantics, can lead to better performance in certain scenarios.

How can I learn the new syntax of C++?

There are various resources available for learning the new syntax of C++, including online tutorials, documentation, and books. It is also helpful to practice writing code using the new syntax and to seek guidance from experienced programmers.

Will the new syntax be adopted by all C++ compilers?

Most modern C++ compilers have already implemented the new syntax, but there may be some variations in how certain features are supported. It is important to check the compatibility of the compiler you are using with the specific features you want to use in your code.

Similar threads

Replies
25
Views
2K
Replies
35
Views
3K
Replies
89
Views
5K
Replies
23
Views
2K
Replies
1
Views
2K
Replies
19
Views
1K
Replies
45
Views
5K
Replies
5
Views
2K
Replies
17
Views
2K
Back
Top