can not refer to the addresses of constructors - c++

A constructor is a 'special' member function whose task is to initialize the objects of its class.
it is special because its name is the same as class name. the constructor is invoked whenever
an
object of its associated class is created.it is called constructor because it constructs the value of data
members of class.
A constructor is declared and defined as follows:
//class with a constructor
class integer
{
int m,n;
public:
integer(void); // constructor declared
};
integer::integer(void)// constructor defined
{
m=0;n=0;
}
We can not refer to their addresses but why?

I think in C/C++ we have a concept of pointers to functions and since constructor is a special member function , what they mean is we can not use pointers to functions as in the case of general functions
Hope it may help you

Because the language doesn't allow any way to take the address of a constructor.
Or, if you're asking why it's not allowed: because there's no reason to do so. You'd only take the address of a function in order to call it, and you never call a constructor directly. It's only called indirectly, as a result of creating an object.

Related

How can I declare an object in a class, that needs another in its constructor?

I want to declare two objects from two different classes inside my private section of my class. The problem I have is that the second object should take the first object in a constructor. So here is the example of my class private section:
class FactorGraph
{
private:
gtsam::ISAM2Params _parameters();
gtsam::ISAM2 _isam(_parameters);
The _parameters object should be passed as an argument for the _isam object but from my knowledge that will not be possible as C++ does not allow this. Is there a slick way to do so?
Initialize your second object in the constructor (or better both):
FactorGraph::FactorGraph()
: _parameters{}, _isam{_parameters}
{ }
The initialization happens in the same order in which the members are listed in your class (regardless of the order of this list(!), so it's a good idea to keep the same order here, your compiler may even warn you otherwise), which here guarantees that _isam won't get anything uninitialized. (I'm not aware of such guarantees if you just define your objects in your class declaration.)
From the comments, thanks #drescherjm: In your class, just declare your objects without initializers:
class FactorGraph
{
private:
gtsam::ISAM2Params _parameters;
gtsam::ISAM2 _isam;
When you declare them without initializers, they should be initialized in the constructor instead. They do not need to be default-constructible in order to do this, the objects gets initialized only once (in the constructor)
Then if you have more constructors, don't forget to either do that everywhere or forward to this one:
FactorGraph(int) : FactorGraph{}, /* other initializers */ { }

Structure C++ meaning stuck

This is really question on C++ language, what does SNeuron(int NumInputs); mean inside the structure? I'm not c++ programer and this construction inside structure looks strange to me. Can anybody explain it what it could be for? I already tried google.
struct SNeuron
{
//the number of inputs into the neuron
int m_NumInputs;
//the weights for each input
vector<double> m_vecWeight;
//ctor
SNeuron(int NumInputs);
};
A struct in C++ is exactly the same as a class, except that all members of a struct are public by default.
So what you are seeing here is simply a constructor declaration for the struct.
The reason, I believe, is to make interoperability with C easier.
It's simply declaring a constructor for the struct SNeuron. This is called a prototype method, and won't wok unless it's implemented later on. It could be implemented inside the class by saying
SNeuron(int NumInputs) {
// Constructor code
}
or outside like this:
SNeuron::SNeuron(int NumInputs) {
// Constructor code
}
The main use of this would be to initialize the fields m_NumInputs and m_vecWeight.
When an instance of the structure is created, it need to be "constructed" (i.e. initialized), that is done by having constructor functions, which are automatically called by the compiler when an instance is created.
For example, in the following declaration and definition of a variable using the structure, the constructor will be called:
SNeuron myNeuron(5); // Creates the instance and calls the constructor function
That is simply a constructor. A constructor is basically a mechanism by which you initialize all the data members of a class when an object of that class type is created.
You can write constructors for both struct and class.
But that constructor which you declared in your code is not the default constructor because a default constructor is that constructor which takes no arguments.

Can we say Constructor Creates Objects?

Someone told me that constructor creates the objects. But on internet I searched that constructor executed when objects created.. Can you explain about this? I'm new to C++
In C++ a constructor is a special kind of class member function that
is executed when an object of that class is instantiated.
Constructors are typically used to initialize member variables of the
class to appropriate default values, or to allow the user to easily
initialize those member variables to whatever values are desired.
So when you call the constructor you have an already instantiated object, so the constructor doesn't create the object, nor creates the objects variables, it is simply used to initialize the variables inside that object (or to make some task you want to before the object is used).
EDIT: Also:
A constructor performs its work in this order:
It calls base class and member constructors in the order of
declaration.
If the class is derived from virtual base classes, it
initializes the object's virtual base pointers.
If the class has or
inherits virtual functions, it initializes the object's virtual
function pointers. Virtual function pointers point to the class's
virtual function table to enable correct binding of virtual function
calls to code.
It executes any code in its function body.
Check these links for more infos:
http://www.learncpp.com/cpp-tutorial/85-constructors/
https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx
https://isocpp.org/wiki/faq/ctors
class a{int a = 0;int b = 0;} a obj = new a();
in above code
your obj is created memory for obj is allocated in stack and then constructor
code is execute

Is the C++ default constructor always called, as indicated in C++ Primer?

I'm newbie to C++. Don't mind this stupid question:
In C++ primer 4th edition (Stanley Lipmann) on page 52, there is a sentence which says:
The default constructor is used regardless of where a variable is defined.
Can anyone explain a bit more? This statements seem like it is missing something.
From the book itself:
Each class may also define what happens if a variable of the type is defined but an initializer is not provided. A class does so by defining a special constructor, known as the default constructor. This constructor is called the default constructor because it is run "by default;" if there is no initializer, then this constructor is used. The default constructor is used regardless of where a variable is defined.
(my italics).
So you're in a section of the book where they're already talking about default constructors (as should be evident in some of the other answers, the default constructor is most definitely not always used).
All that the book is saying is, in those situations where the default constructor is used, it makes no difference at all where the variable is defined (inside or outside functions, inside or outside classes, inside braces such as loops, selection statements or even naked braces, and so on).
If you have a class Object:
class Object
{
public:
int x;
Object() { x = 5; }
};
and you instantiate one in a function like this:
void foo()
{
Object obj;
// obj.x == 5
}
The default constructor will be used. Objects are also constructed with the default constructor when you declare them within another class and instantiate that other class:
class AnotherObject
{
public:
Object obj;
};
void bar()
{
AnotherObject another;
// another.obj.x == 5
}
Presumably you mean Stanley Lippman?
Anyway, though I don't have a copy handy to check, I'd guess he means if you have something like:
myclass X;
...the X object will be initialized with the default ctor, regardless of whether the object is global (outside any function), local to a function, or local to some other scope within a function (e.g., in a for loop).
Contrast this with a built-in type line int, which has rather more complex rules: a global int (one defined outside any function) or one defined inside a function, but with static storage class, will be initialized to zero, but an int defined with automatic storage (defined inside a function, without specifying static) is "default initialized", which (in this case) means it's not initialized to a predictable value.
$12.1
The default constructor (12.1), copy constructor and copy assignment operator (12.8), and destructor (12.4) are special member functions. The implementation will implicitly declare these member functions for a class type when the program does not explicitly declare them, except as noted in 12.1. The implementation will implicitly define them if they are used, as specified in 12.1, 12.4 and 12.8. Programs shall not define implicitly-declared special member functions. Programs may explicitly refer to implicitly declared special member functions. [Example: a program may explicitly call, take the address of or form a pointer to member to an implicitly declared special member function.

Calling member functions from a constructor

I know this question has a similar title to this: C++: calling member functions within constructor? but I am asking a more general question.
Is it good practice to call member functions from within a constructor? It makes reading the code easier and I prefer the encapsulation type way of doing it (ie. each block of code has a single objective).
An illustrative example, in python:
class TestClass:
def __init__(self):
self.validate()
def validate(self):
# this validates some data stored in the class
Is this a better way of doing it than writing the validate code inside the constructor? Are there drawbacks to this method? For example is it more costly with the function overhead?
I personally prefer it for readability but that's just my preference.
Cheers
I don't think there is anything inherently wrong in calling member functions from a constructor provided that they are not virtual functions.
The problem with calling virtual member functions from a constructor is that a subclass can override the function. This will cause the constructor to call the overridden implementation in the subclass, before the constructor for the subclass part of the object has been called.
In Java, any one of the private, static or final access modifiers will make the method safe to call from a constructor by preventing a virtual call to the superclass method. I don't think these techniques are available in Python.
There is at least one associated "gotcha" you should be aware of:
N3797 12.6.2/14
Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result
of the operation is undefined. [Example:
class A {
public:
A(int);
};
class B : public A {
int j;
public:
int f();
B() : A(f()), // undefined: calls member function
// but base A not yet initialized
j(f()) { } // well-defined: bases are all initialized
};
class C {
public:
C(int);
};
class D : public B, C {
int i;
public:
D() : C(f()), // undefined: calls member function
// but base C not yet initialized
i(f()) { } // well-defined: bases are all initialized
};
— end example]
The main problem with this is that the member function has to work with an object that may be only partially initialized. And if it (even accidentally) passes a reference to the object somewhere else, other code has to od the same. This can get pretty confusing and error-prone, especially once you start overriding such a function in a subclass.
So in general, this practice should be avoided or at least confined to functions that can't be overriden, and they should never pass a reference to the object being constructed to any other code.
I'm more familiar with C++ than Python, but I see no problem with calling member functions from constructors, especially when this practice is able to factor out similar code from multiple constructors. Anything that reduces redundancy is good in my books.
From a readability point of view it is definitely better. One thing you might have to ask yourself here though is whether the validate method is allowed to run after the object is initialized. If that is not the case, you can a) use some kind of private initialized variable or b) use the Builder pattern to get your objects into a valid state before using them.
Make sure the function is private. You do not want to mess with subclasses overriding it (Unless this is desired by design, in which case make it abstract/virtual).
first, this member function cannnot be virtural function,
second, this member function must be implemented in the same file, if you declare it in *.h, then implement it in *.cpp, gcc/clang will report this error undefined reference to