3

I'm learning c++ and I have problem with basics. How to init object in different class?

For example I have code:

class A { private: static int num; static string val; public: A(int n, string w) { num = n; val = w; } }; 

I want to create object A in class B, so I have try like this:

class B { private: A objA; public: B(int numA, string valA){ objA = new A(numA, valA); } }; 

Different ways(same constructor):

 public: B(A obA){ objA = obA; } 

or

 public: B(int numA, string valA){ objA = A(numA, valA); } 

Always I'm getting error: No default constructor for exist for class "A". I've read that default constructor is constructor without any arguments, but I give them, so why it is searching default?

3
  • 1
    What's a LiczbaHeks? Read about constructor initializer lists. And it doesn't look like you want num and val to be static data members. Commented Apr 9, 2015 at 21:13
  • 1
    Yes, you need an initializer list. And don't use new like that. And, you could always add a default constructor, but in this case you shouldn't need it. Commented Apr 9, 2015 at 21:14
  • I edit that "LiczbaHeks". It is from my code, I haven't seen this. Sorry. Commented Apr 9, 2015 at 21:17

2 Answers 2

3

If you want to learn C++ ... forget java. C++ variables are values, not pointers in reference disguise.

objA = new something is an abomination, since objA is A and not A*.

What you need is just explicitly construct objA with proper parameter

class B { private: A objA; public: B(int numA, string valA) :objA(numA, valA) { } } }; 

For more reference see http://en.cppreference.com/w/cpp/language/initializer_list

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it is a pity that I can't accept two answer. Vlad was first. Thanks any way!
2

You can do it the following way

class B { private: A objA; public: B(int numA, string valA) : objA( numA, valA ) {} }; 

2 Comments

Thanks! I can only say.. that c++ is strange :D
@Ojmeny Yes, it is not an intuitively clear language.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.