I have been programming some in Java earlier, and i'm now trying to learn c++, but having trouble with understanding pointers, deep-/shallow copy, copy constructor, assignment operator and those c++ specific things. It's not really the code itself, its more how they relate and why / when they are needed.
So i tried to make a easy example for myself, so i would get the hang of it but i can't get it to work, it keeps crashing.
Here's the code:
class A
{
public:
A();
A(B* v);
A(const A &o);
virtual ~A();
void print(std::ostream &o);
A& operator=(A& o);
friend std::ostream &operator<<(std::ostream &stream, A p);
protected:
private:
B *value;
};
void A::print(std::ostream &o)
{
value->print(o);
}
A& A::operator=(A& o)
{
std::cout << "Operatorn"<< std::endl;
this->value = o.value;
}
A::A()
{
//ctor
}
A::A(B* v)
{
this->value = v;
std::cout << "B konstruktor" << std::endl;
}
A::A(const A& o)
{
std::cout << "Kopieringskonstruktor" << std::endl;
this->value = o.value;
}
A::~A()
{
if(value!=NULL) delete value;
std::cout << "Deletar value" << std::endl;
}
--------------------------------------------------
class B
{
public:
void print(std::ostream &o);
B();
B(int i):value(i){}
virtual ~B();
protected:
private:
int value;
};
--------------------------------------------------
std::ostream &operator<<(std::ostream &stream, A p)
{
p.print(stream);
return stream;
}
int main()
{
vector<A> vecA;
ostream_iterator<A> it(cout);
vecA.push_back(A(new B(5)));
vecA.push_back(A(new B(10)));
copy(vecA.begin(), vecA.end(),it);
return 0;
}
Edit 1
Some clarification, a similar problem to this is a homework assignment for me. Where i should have a holder-class A containing the value *B. And B is inherited to C and D, enabling me to place both class C and D into value *B.
I simplified and striped the code from this, since i didn't think it was relevant to the issue i'm having with memory and assignment.