Reputation: 3405
How do I initialize pointer class B foo
inside class A? I am new to C++.
Header.h
namespace Core
{
enum type
{
Left, Right
};
template<type t>
class B
{
public:
B(int i);
private:
type dir;
int b = 12;
};
class A
{
public:
B<Left> *foo;
};
}
Source.cpp
namespace Core
{
template<type t>
B<t>::B(int i)
{
dir = t;
b = i;
}
}
int main()
{
Core::A *a = new Core::A;
a->foo = new Core::B<Core::Left>(10);
return 0;
}
Upvotes: 1
Views: 8925
Reputation: 595402
Source.cpp
needs a #include "Header.h"
statement, and Header.h
needs a header guard.
Also, you need to move the implemention of B
's constructor into the header file. See Why can templates only be implemented in the header file?.
Try this:
Header.h:
#ifndef HeaderH
#define HeaderH
namespace Core
{
enum type
{
Left, Right
};
template<type t>
class B
{
public:
B(int i);
private:
type dir;
int b = 12;
};
class A
{
public:
B<Left> *foo;
};
template<type t>
B<t>::B(int i)
{
dir = t;
b = i;
}
}
#endif
Source.cpp
#include "Header.h"
int main()
{
Core::A *a = new Core::A;
a->foo = new Core::B<Core::Left>(10);
//...
delete a->foo;
delete a;
return 0;
}
I would suggest taking it a step further by inlining B
's constructor and giving A
a constructor to initialize foo
:
Header.h:
#ifndef HeaderH
#define HeaderH
namespace Core
{
enum type
{
Left, Right
};
template<type t>
class B
{
public:
B(int i)
{
dir = t;
b = i;
}
private:
type dir;
int b = 12;
};
class A
{
public:
B<Left> *foo;
A(int i = 0)
: foo(new B<Left>(i))
{
}
~A()
{
delete foo;
}
};
}
#endif
Source.cpp
#include "Header.h"
int main()
{
Core::A *a = new Core::A(10);
//...
delete a;
return 0;
}
Upvotes: 1
Reputation: 206567
How do I initialize pointer class B foo inside class A?
Construct a B<Left>
with an assumed value.
class A
{
public:
B<Left> *foo = new B<Left>(0);
};
Add a constructor of A
that accepts an int
that can be used to construct a B<Left>
.
class A
{
public:
A(int i) : foo(new B<Left>(i)) {}
B<Left> *foo;
};
Before you down too far into using pointers to objects in your classes, consider the following:
shared_ptr
and unique_ptr
.Upvotes: -1