-2

I'm writing Class A, and it has a constructor that initializes values. I'm creating an instance of Class A in another Class B like so:

#include <iostream>

class A {
public:
    int value;

    A(int value) {
        this->value = value;
    }

    void print_string() {
        std::cout << "talking...";
    }
};

class B {
public:
    A new_a;

    B(int b_value) {
        new_a = A(b_value);
    }

    void print_from_A() {
        new_a.print_string();
    }
};

int main() {
    B b(23);
    b.print_from_A();
    return 0;
}

However, I have syntax errors with this code, it says no default constructor exist for class A . What I want is:

1 to make instance of class A global in class B so other methods in class B can access it.

2 to initialize values in class A through it's constructor by calling it in, and passing the values through class B

John Sall
  • 1,027
  • 1
  • 12
  • 25
  • Please add the text of the error messages to the question. Also, try to only ask one question per question. – cigien Jan 11 '21 at 11:47

1 Answers1

2

There is no default constructor for A. You should use a member initializer lists

    B(int b_value): new_a(b_value) {
    }

Your constructor

    B(int b_value) {
        new_a = A(b_value);
    }

tries to default initialize new_a and then to assign A(b_value) to it. But default initialization is not possible without default constructor. You should always use member initializer lists:

    A(int value): value(value) {
    }
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • okay it worked! thanks. another question though on the side, can I initialize class A values by calling other methods in class B other than the constructor? – John Sall Jan 11 '21 at 11:59
  • @JohnSall No, initialization of member variables happens in the constructor. – Thomas Sablik Jan 11 '21 at 12:00