constructors

when creating an object with a constructor, as far as i understand, we don't name the object. so how can we reference that object later.
i know two ways to create objects
1
2
3
4
5
//first way 
class object(argument, argument);
//second way
copyConstructor(argument, argument);

in the case of the second method, is there any way to identify the object?
What are you talking about?
1
2
3
4
5
6
7
8
9
10
void func( MyClass ); // declare function

MyClass one; // name: "one", created with default constructor
MyClass two( "answer", 42 );  // name: "one", created with custom constructor
MyClass three {two}; // name: "three", created with copy constructor

func( MyClass( "other", 7 ) ); // unnamed temporary that is passed to function

MyClass* p = new MyClass( "yes", 3 ); // unnamed, pointed to by "p"
delete p; // destruct the unnamed 
@keskiverto
thank you for your fast reply. i will try this. im not too familiar with the new operator so i hadn't thought of this.
You don't want to know the new. Modern C++ has better, safer ways to obtain memory dynamically.


Another tidbit:
1
2
3
4
5
6
7
8
9
void func( MyClass obj ) // implementation of same function as before
{
  // does something with obj
}

int main() {
  MyClass one;
  func( one );
}

That code uses two constructors. The "one" is default constructed. The "obj" is copy constructed.
class is a c++ keyword that creates a TYPE. NOT an object, but a TYPE.
so
class foo {bunch of junk}; //no object
foo x; //x is an object of type foo! the constructor for foo is called here quietly!
note how 'foo' is not the object name, its the type name, like int x, double x, not the name of any variables.

a copy constructor is a little different:
foo y;
foo x = y; //copy constructor is used instead of regular one. I suggest you table the copy constructor idea for a little while (due to https://en.cppreference.com/w/cpp/language/rule_of_three).

you don't need the new operator to get an object. That is a whole new can of worms, dynamic memory. Everything above shows examples of the same idea I am giving (that the class is the type, and the variables are elsewhere when you USE the type) -- whether you use dynamic memory or make a C array or stuff them into a container or just have 1 ... its exactly the same as an integer in regards to these ideas and done the same way (foo x[100] for a c array, vector<foo> x; for a container, foo* fp for a pointer/dynamic memory, and on and on... all look exactly like int as you have hopefully already seen and learned most of these).
Last edited on
Topic archived. No new replies allowed.