0

In Java, Object takes the place of various class objects, but casting is needed. In the piece of code below, auto seems to be doing the same only that it does not need to be casted with a type variable.

It seems like a lazy (efficient?) way to progress through code. I might get accustomed to using auto instead of a specific type (in the example below, it would be 'int index'). There might be an occasion(s) where such incorporation would not be recommended.

piece of code:

vector<int> fCount(1001,0);
for(auto index : list)
{
    ++fCount[index];
}
  • auto can be used when the type can be inferred, it just gets replaced with the concrete type at compile time - there is no runtime difference – Dominic Mar 02 '22 at 19:15
  • 3
    No, it is not related at all. There is no equivalent of `Object` in C++. – user17732522 Mar 02 '22 at 19:15
  • 3
    Furthermore, the best advice to give is to completely forget everything you know about Java while learning C++. The syntax is very similar, but C++'s objects work in fundamentally different ways. It is a safe bet that every assumption that's made about C++'s objects, because that's how Java's objects work, will result in non-stop confusion, frustration and tears. Examples: why do changes to objects made in a function are "lost" when the function returns? It's because C++ is not Java. Why linking templates fails, I'm compiling their `.cc` files! Because C++ is still not Java, etc... – Sam Varshavchik Mar 02 '22 at 19:21
  • C++ has no unique base class like `Object` in Java. But I wanted to note that some C++ frameworks actually do provide a root class from which all classes derive: `CObject` in MFC, `QObject` in Qt, `BaseObject` in ALF, and probably others. – prapin Mar 02 '22 at 19:25
  • 2
    `auto` is `var`. – chris Mar 02 '22 at 19:28
  • Also, don't use Java as a model in writing C++ code. As mentioned, if you use Java as a model, the C++ code will have one or more of these traits: 1) Inefficient, 2) Buggy, 3) The code will look weird to a C++ programmer. – PaulMcKenzie Mar 02 '22 at 20:00

1 Answers1

0

Actually NO. Object in Java differs from auto in C++. In C++, auto keyword only can be applied to any type that can be deduced in compile-time, not run-time. In the code snippet you given, although the index is deduced to be an int, but if you try to use to use index in wherever context that the int cannot be used, compiler will complain.

auto is just a syntactic sugar that modern C++ offers, that you do not have to specify the type when compiler can deduce from the expression. Although you do not have to specify the type explicitly, compiler specifies it in implicit way. After the compiler deduced the type, you cannot use the variable as other type(if it cannot be implictly converted)

K.R.Park
  • 1,015
  • 1
  • 4
  • 18
  • Uh, oh... I did not know that https://stackoverflow.com/questions/7576953/c-auto-keyword-why-is-it-magic answers current question. – K.R.Park Mar 02 '22 at 19:38