I know the this pointer will point to the object instance that currently in, but I don't know how to implement it.
And I found that in standard 7.5.2 said:
The keyword this names a pointer to the object for which an implicit object member function ([class.mfct.non.static]) is invoked or a non-static data member's initializer ([class.mem]) is evaluated.
but in 12.2.2 said constructors do not have implicit object parameter, then why I can use this pointer in constructor?
then I have several question comming, so my question is:
Does the this pointer belongs to the class?
I think the answer is NO, but I wanna confirm it.
Does all class instance shared the constructors and destructor?
I knew that the class instance will share the member function, does it same on constructors and destructor?
How the this pointer was implemented?
Is there something like virtual table to maintain the this pointer?
Why I can use the this pointer in constructor?
The this point to the implicit object, but constructor didn't have the implicit object parameter, then how could the this pointer worked well?
Any additional supplements and recommendations are appreciated.
Edit:
This stackoverflow helps me a lot : Does a constructor also have an implicit this parameter
but I don't know how to implement it.
this pointer is a feature of the C++ language. If you aren't implementing C++, then you don't need to "implement" this pointer. If you want to know how to implement C++, there are open source C++ compilers available.
why I can use this pointer in constructor?
Constructor is a non-static member function. You can use this in non-static member functions.
but in 12.2.2 said constructors do not have implicit object parameter
Quoted rule is prefaced: For the purposes of overload resolution.... It doesn't apply to anything other than overload resolution.
Does the this pointer belongs to the class?
There is no concept of "belongs" in the language.
Does all class instance shared the constructors and destructor?
There is no concept of sharing functions in the language.
How the this pointer was implemented?
The language doesn't describe how to implement itself. It describes how the program written in the language shall or may behave.
Why I can use the this pointer in constructor?
See above.
Related
Coming from Java, C++ is breaking my brain.
I need a class to hold a reference to a variable that's defined in the main scope because I need to modify that variable, but I won't be able to instantiate that class until some inner loop, and I also won't have the reference until then. This causes no end of challenges to my Java brain:
I'm used to declaring a variable to establish its scope, well in advance of knowing the actual value that will go in that variable. For example, creating a variable that will hold an object in my main scope like MyClass test; but C++ can't abide a vacuum and will use the default constructor to actually instantiate it right then and there.
Further, given that I want to pass a reference later on to that object (class), if I want the reference to be held as a member variable, it seems that the member variable must be initialized when it's declared. I can't just declare the member variable in my class definition and then use some MyClass::init(int &myreference){} later on to assign the reference when I'll have it in my program flow.
So this makes what I want to do seemingly impossible - pass a reference to a variable to be held as a member variable in the class at any other time than instantiation of that class. [UPDATE, in stack-overflow-rubber-ducking I realized that in this case I CAN actually know those variables ahead of time so can side-step all this mess. But the question I think is still pertinent as I'm sure I'll run into this pattern often]
Do I have no choice but to use pointers for this? Is there some obvious technique that my hours of Google-fu have been unable to unearth?
TLDR; - how to properly use references in class member variables when you can't define them at instantiation / constructor (ie: list initialization)?
Declare reference member variable that you won't have at instantiation
All references must be initialised. If you don't have anything to initialise it to, then you cannot have a reference.
The type that you seem to be looking for is a pointer. Like references, pointers are a form of indirection but unlike references, pointers can be default initialised, and they have a null state, and can made to point to an object after their initialisation.
Important note: Unlike Java references, C++ references and pointers do not generally extend the lifetime of the object that they refer to. It's very easy to unknowingly keep referring to an object outside of its lifetime, and attempting to access through such invalid reference will result in undefined behaviour. As such, if you do store a reference or a pointer to an object (that was provided as an argument) in a member, then you should make that absolutely clear to the caller who provides the object, so that they can ensure the correct lifetime. For example, you could name the class as something like reference_wrapper (which incidentally is a class that exists in the standard library).
In order to have semantics similar to Java references, you need to have shared ownership such that each owner extends the lifetime of the referred object. In C++, that can be achieved with a shared pointer (std::shared_ptr).
Note however, that it's generally best to not think in Java, and translate your Java thoughts into C++, but it's better to rather learn to think in C++. Shared ownership is convenient, but it has a cost and you have to consider whether you can afford it. A Java programmer must "unlearn" Java before they can write good C++. You can also subsitatute C++ and Java with most other programming languages and same will apply.
it seems that the member variable must be initialized when it's declared.
Member variables aren't directly initialised when they are declared. If you provide an initialiser in a member declaration, that is a default member initialiser which will be used if you don't provide an initialiser for that member in the member initialiser list of a constructor.
You can initialise a member reference to refer to an object provided as an argument in a (member initialiser list of a) constructor, but indeed not after the class instance has been initialised.
Reference member variables are even more problematic beyond the lifetime challenges that both references and pointers have. Since references cannot be made to point to other objects nor default initialised, such member necessarily makes the class non-"regular" i.e. the class won't behave similar ways as fundamental types do. This makes such classes less intuitive to use.
TL;DR:
Java idioms don't work in C++.
Java references are very different from C++ references.
If you think that you need a reference member, then take a step back and consider another idea. First thing to consider: Instead of referring to an object stored elsewhere, could the object be stored inside the class? Is the class needed in the first place?
In C++ is it true that if you instantiate an object of a class, that for every
object all of methods of the class are copied for the new object?
I tried to point to a method of a class with two different objects, but I'd problems
with pointer to member.
Any idea?
In C++ is it true that if you instantiate an object of a class, that for every object all of methods of the class are copied for the new object?
No, member functions are not usually copied anywhere. A different implicit parameter this is instead passed to any non-static member function, for each object of that class-type.
No, that is absolutely not true.
Class instances (objects) contain data members. Function members look like they're "in" the class, but that's only for scoping and such: your function code doesn't "exist" inside the type, and it certainly doesn't exist inside the object†.
† I think it could, theoretically, in that the standard doesn't outright forbid it. But honestly, no. Just no.
The code for a class exists only once.
For getting a pointer to a member function (probably what you meant by method), take a look at std::function, and for attaching the function call to different objects, take a look at std::bind.
Can references be used to implement function overriding?
Can I have a base-class reference that points to a derived-class object, and then get the feature of late binding?
Yes, but polymorphism isn't automatic the way it is in some languages like Java. You have to declare the function virtual in the base class.
Yes. The reason is that, in C++, the derived class object contains a hidden pointer to a record that details the object's actual type. Both the pointer and the record remain, even when a reference binds the object in question.
This assumes, as #Simon observes, that you have declared the function virtual in the base class. (Otherwise, the needed hidden pointer does not exist.)
I have a C++ object declared in my Objective-C class.
The C++ object has only one constructor that takes several parameters.
In C++ code I would parse the parameters to the constructor in the initializer list of the class that contains it.
How do I do the same in Objective-C?
When I compile I get an error telling me that there is no appropriate default constructor for my C++ object, as you would expect.
I don't think you are able to do something like that in Objective-C, because there are no constructors and initializer lists there. But you can use std::shared_ptr or other smart pointer to store a pointer to your class and create the object itself in init method
You could change the object to a (smart) pointer for this object type. Then you can delay the construction of the object to the moment you see fit.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why do we not have a virtual constructor?
I know this has been asked before but I didn't understand the complex technical words used in the other answers.
I read on a community the reason that constructors cannot be virtual is
The ‘virtual’ mechanism works on a logically complete (completely constructed) object. We know that we use constructors to logically initialize our objects. In other words, the object is not completely constructed until the constructor has finished executing. Thus, we can’t have virtual constructors.
There is a misconception that by then virtual table is incomplete so we can’t have virtual constructors. Just before the constructor starts executing the virtual table is properly constructed and the ‘this’ pointer passed to the constructors. Moreover, virtual table mechanism is implementation depended, and finds no place in the C++ standard. And hence, to argue over this issue using the virtual table concept is illogical.
Now, as the constructor finishes executing any other function can be virtual. Destructor is no exception to this rule as it is a function. Virtual destructors are required in case we use a base class pointer to refer to a derived class object, use it, and then delete it. If we have virtual destructor, using ‘delete’, a chain of destructors is called starting from the derived to the base. But, had there been no ‘virtual’ in destructor only the base class destructor is called (and not the derived). This (may) generate inconsistencies in the program.
Is the above reason correct? The answer doesn't talk about the static and dynamic types of objects.
Virtual constructors don't make sense and aren't necessary. The only time you call a constructor is when creating an object. You need to know the type of an object in order to create it, so the static and dynamic types are the same, and the correct constructor to call is the one for that type.
That's why they aren't necessary. Why they don't make sense, is that when creating an object, base class constructors are called as well as derived class constructors. If the base class constructor was overridden in the derived class, is that supposed to mean that the base class constructor isn't called after all?
Other languages have virtual constructors, perhaps because constructors in those languages are methods, and they only have virtual invocation for non-static methods. But those other languages (Java and Python spring to mind) have to introduce special rules that constructors must/should construct their base class explicitly as a call from the constructor. C++ just does it (perhaps in an initializer list, if the base class constructor requires parameters), using non-virtual constructors, and there is no option to enter the body of the constructor with uninitialized base class sub objects.
To quote from The C++ Programming Language:
To construct an object, a constructor
needs the exact type of the object it
is to create. Consequently, a
constructor cannot be virtual.
Furthermore, a constructor is not
quite an ordinary function. In
particular, it interacts with memory
management routines in ways ordinary
member functions don’t. Consequently,
you cannot have a pointer to a
constructor.
It must be interesting to note that C++ do have an idiom called virtual constructor. You can read more about that here.
Yes, the reason is you need to have a pointer/reference to a complete object already before you can call a virtual function. When the constructor is being invoked there's no complete object yet. Even more, when you do new SomeClass() you don't even have a pointer yet - the pointer is returned upon the new statement is completed successfully.
The virtual keyword cannot be applied to a constructor since a constructor turns raw bits into a living object, and until there is a living object against which to invoke a member function, the member function cannot possibly work correctly. Instead of thinking of constructors as normal member functions on the object, imagine that they are static member functions that create objects. - C++ FAQs