C++ copy constructor by pointer - copy-constructor

Hello i want to create a new class variable that is a pointer and initialize it by copy constructor. Though I know how copy constructor works by refernce, i cannot figure out how to do it. Can you help me?
For example I have this definition:
class A{
public:
int a;
private:
};
and in another code segment i do the following:
A *object= new A;
A->a=10;
A *newobject= new A(*object);
but i get a segmentation fault. Can you help me?
I also tried:
A *newobject= new A(&(*object));
but it doesn't work either.

These lines in your example shouldn't even compile:
A *object= new A;
A.a=10;
What you mean is
Foo *object = new Foo;
object->a = 10;
Right?
Edited to add:
What happens when you try the code posted by #Alok Save?

With this kind of simple example, the following which uses the default bit wise copy constructor works fine.
The simple class looks like
class Bclass {
public:
int iValue;
};
And the code to use the copy constructor looks like:
Bclass *pObject = new Bclass;
pObject->iValue = 10;
Bclass *pObject2 = new Bclass (*pObject);
Using Microsoft Visual Studio 2005, the above works fine.
See also Implementing a Copy Constructor.
See also Copy constructor for pointers to objects.

Since the class name is Foo and not A, a Foo object should be created.
class Foo{
public:
int a;
private:
};
Foo *object= new Foo;
object->a=10;
Now since object is a pointer to class Foo, the -> operator should be used.

Related

What is the difference between Class myVar = new Class() vs var myVar = new Class() in Dart?

I'm trying to study Dart and I noticed in the online documentation that if the class has custom constructor the example of initializing the class is like this:
Employee emp = new Employee();
Now my question is what is the difference between this code and the previous one?
var emp = new Employee();
I tested both in online sandbox and constructors are both invoked. When do I use which code?
PS I'm not sure if this was already asked since I don't know the term of it in Dart.
It doesn't make any difference because Dart is inferring the variable type from the value you assign. You would typically mention a class when you don't initialize the variable :
var value; // This is a dynamic variable of null value
int value; // This is an int variable of null value
More on inference and the Dart type system

Way to defensive check value assigned to public const variable in immutable class in C++17?

Coming back to C++ after a hiatus in Java. Attempting to create an immutable object and after working in Java, a public const variable seems the most sensible (like Java final).
public:
const int A;
All well and good, but if I want to defensive check this value, how might I go about it. The code below seems strange to me, but unlike Java final members, I can't seem to set A in the constructor after defensive checks (compiler error).
MyObj::MyObj(int a) : A(a) {
if (a < 0)
throw invalid_argument("must be positive");
}
A public const variable for A seems like a clearer, cleaner solution than a getter only with a non const int behind it, but open to that or other ideas if this is bad practice.
Your example as it stands should work fine:
class MyObj {
public:
const int var;
MyObj(int var) : var(var) {
if (var < 0)
throw std::invalid_argument("must be positive");
}
};
(Live example, or with out-of-line constructor)
If you intend that MyObj will always be immutable, then a const member is
probably fine. If you want the variable to be immutable in general, but still have the possibility to overwrite the entire object with an assignment, then better to have a private variable with a getter:
class MyObj {
int var;
public:
MyObj(int var) : var(var) {
if (var < 0)
throw std::invalid_argument("must be positive");
}
int getVar() const { return var; }
};
// now allows
MyObj a(5);
MyObj b(10);
a = b;
Edit
Apparently, what you want to do is something like
MyObj(int var) {
if (var < 0)
throw std::invalid_argument("must be positive");
this->var = var;
}
This is not possible; once a const variable has a value it cannot be changed. Once the body ({} bit) of the constructor starts, const variables already have a value, though in this case the value is "undefined" since you're not setting it (and the compiler is throwing an error because of it).
Moreover, there's actually no point to this. There is no efficiency difference in setting the variable after the checks or before them, and it's not like any external observers will be able to see the difference regardless since the throw statement will unroll the stack, deconstructing the object straight away.
Generally the answer by N. Shead is the regular practice - but you can also consider:
Create domain-specific types and use them instead of general primitives. E.g., if your field is a telephone number, have a type TelephoneNumber which, in its constructor (or factory), taking a string, does all the telephone number validation you'd like (and throws on invalid). Then you write something like:
class Contact {
const TelephoneNumber phone_;
public:
Contact(string phone) : phone_(phone) { ... }
...
When you do this the constructor for TelephoneNumber taking a string argument will be called when initializing the field phone_ and the validation will happen.
Using domain-specific types this way is discussed on the web under the name "primitive obsession" as a "code smell".
(The problem with this approach IMO is that you pretty much have to use it everywhere, and from the start of your project, otherwise you start having to have explicit (or implicit) casting all over the place and your code looks like crap and you can never be sure if the value you have has been validated or not. If you're working with an existing codebase it is nearly impossible to retrofit it completely though you might just start using it for particularly important/ubiquitous types.)
Create validation methods that take and return some value, and which perform the validation necessary - throwing when invalid otherwise returning its argument. Here's an example validator:
string ValidatePhoneNumber(string v) {
<some kind of validation throwing on invalid...>
return v;
}
And use it as follows:
class Contact {
const string phone_;
public:
Contact(string phone) : phone_(ValidatePhoneNumber(phone)) { ... }
I've seen this used when an application or library is doing so much validation of domain-specific types that a small library of these domain-specific validator methods has been built up and code readers are used to them. I wouldn't really consider it idiomatic, but it does have the advantage that the validation is right out there in the open where you can see it.

Variable unknown when not initialized in the declaration

I ran into this today, and I was wondering if something is going wrong here.
module example
public rel[str file, AstNode namespace] relFileNamespace;
public void InitGlobals()
{
relFileNamespace = {};
}
Then in the console:
rascal>import example;
ok
rascal>InitGlobals();
ok
rascal>relFileNamespace
|stdin:///|(0,13,<1,0>,<1,13>): Undeclared variable, function or constructor: relFileNamespace
If I declare it like this it does work.
public rel[str file, AstNode namespace] relFileNamespace = {};
So the question is, why does it have to be initialized in the declaration?
Rascal does not allow uninitialized variables at all, but it should complain about "uninitialized" in that case, not "undeclared"
It is not finding your variable. Could you try adding "example::" before dereferencing?

weird behavior using f# class with redis service stack lib

I'm testing a bit redis using .Net, I've read this tutorial
http://www.d80.co.uk/post/2011/05/12/Redis-Tutorial-with-ServiceStackRedis.aspx
and follow using c# and worked perfect, now when I'm trying translate this to f# I've a weird behavior, first I create a simple f# class (using type didn't work neither but it was expected)...basicaly the class is something like this:
//I ve used [<Class>] to
type Video (id : int, title : string , image : string , url : string) =
member this.Id = id
member this.Title = title
member this.Image = image
member this.Url = url
when I run the code, my db save an empty data, if I use a c# class inside my f# code this work, so I'm sure than the problem is the f# class...How can resolve this without depend c# code inside my f# code
Thanks !!!
Based on your tutorial, it looks like you want your F# Video class to be full of getter and setter properties instead of having a constructor with getters only as it is now (and it is a class, which you can verify by running it through FSI).
You can achieve this using a record type full of mutable fields (which is compiled down to a class type full of public getters and setters):
type Video = {
mutable Id : int
mutable Title : string
mutable Image : byte[]
mutable Url : string
}

Virtual Constructors

Is there any need of Virtual Constructors? If so can any one post a scenario?
If you are talking about virtual destructors in C++ (there isn't any such thing as virtual constructors) then they should always be used if you are using your child classes polymorphically.
class A
{
~A();
}
class B : public A
{
~B();
}
A* pB = new B();
delete pB; // NOTE: WILL NOT CALL B's destructor
class A
{
virtual ~A();
}
class B : public A
{
virtual ~B();
}
A* pB = new B();
delete pB; // NOTE: WILL CALL B's destructor
Edit: Not sure why I've got a downvote for this (would be helpful if you left a comment...) but have a read here as well
http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx
As always: look up at C++ FAQ lite: virtual functions.
It will explain not only "virtual constructor" but destructors/functions too!
This of course, if you wanted C++ in the first place...
There are plenty of scenarios, for example if you want to create GUIs for more than one environment. Let's say you have classes for controls (“widgets”) but each environment actually has its own widget set. It's therefore logical to subclass the creation of these widgets for each environment. The way to do this (since, as has been unhelpfully pointed out, constructors can't actually be virtual in most languages), is to employ an abstract factory and the above example is actually the standard example used to describe this design pattern.
Delphi is one language that supports virtual constructors.
Typically they would be used in a class factory type scenario where you create a meta type i.e. that is a type that describes a type. You would then use that meta type to construct a concrete example of your descendant class
Code would be something like....
type
MyMetaTypeRef = class of MyBaseClass;
var
theRef : MyMetaTypeRef;
inst : MyBaseClass;
begin
theRef := GetTheMetaTypeFromAFactory();
inst := theRef.Create(); // Use polymorphic behaviour to create the class
In what language? In C++ for example the constructors can not be virtual.
The constructor can not be virtual by definition. At the time of constructor call there is no object created yet, so the polymorphism does not make any sense.
In C++, there's no reason for constructors to ever be virtual, because they are static functions. That means they're statically bound, so you have to identify the very constructor function you're calling in order to call it at all. There's no uncertainty and nothing virtual about it.
This also means that, no matter what, you need to know the class that your object is going to be. What you can do, however, is something like this:
Superclass *object = NULL;
if (condition) {
object = new Subclass1();
}
else {
object = new Subclass2();
}
object.setMeUp(args);
... have a virtual function and call it after constructon. This is a standard pattern in Objective-C, in which first you call the class's "alloc" method to get an instance, and then you call the initilializer that suits your use.
The person who mentioned the Abstract Factory pattern is probably more correct for C++ and Java though.
In C++, all constructors are implicitly virtual (with a little extra). That is, the constructor of the base class is called before that of the derived class. So, it's like they're sort of virtual. Because, in a virtual method, if the derived class implements a method of the same signature, only the method in the derived class is invoked.
However, in a constructor, BOTH METHODS ARE INVOKED (see example below).
For a more complete explanation of why this is so, please see Item 9 of Effective C++, Third Edition, By Scott Meyers (Never call a virtual function during construction or destruction). The title of the item may be misleading in relation to the question, but if you read the explanation, it'll make perfect sense.
#include <iostream>
#include <vector>
class Animal {
public:
Animal(){
std::cout << "Animal Constructor Invoked." << std::endl;
}
virtual void eat() {
std::cout << "I eat like a generic animal.\n";
}
//always make destructors virtual in base classes
virtual ~Animal() {
}
};
class Wolf : public Animal {
public:
Wolf(){
std::cout << "Wolf Constructor Invoked." << std::endl;
}
void eat() {
std::cout << "I eat like a wolf!" << std::endl;
}
};
int main() {
Wolf wolf;
std::cout << "-------------" << std::endl;
wolf.eat();
}
Output:
Animal Constructor Invoked.
Wolf Constructor Invoked.
-------------
I eat like a wolf!
Virtual constructors dont make sense in C++ . THis is because in C++ constructors do not have a return value . In some other programming languages this is not the case . In those languages the constructor can be called directly and the constructor has a return value . This makes them useful in implementing certain types of desgin patterns . In C++ however this is not the case .

Resources