Can you assign a value to C++ object without calling attributes?


This Content is from Stack Overflow. Question asked by Sam G

I tried the following code in C++ which compiled but have trouble understanding why:

  1. why am I able to assign a value to an object without calling its attributes?
  2. Would like to understand why the first elem in the vector within foo object changed?
  3. Lastly would appreciate thoughts on whether this way of defining class and setting object values is idiomatic c++
class Foo {
    Foo(float n): a(n){}
    std::vector<float> a;

int main() {
  Foo fooObj(1);
  fooObj.a[0] = 100;

  std::cout << fooObj.a[0] << "n";
  fooObj = 100; // why is this allowed? I thought it is illegal to assign value to object without calling attribute
  std::cout << fooObj.a[0] << "n"; // why does the first element change, is it because a new vector is created?

  return 0;


Check the Answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?