[완료] C++ 에서 생성자 관련 질문입니다..

anster의 이미지

안녕하세요~ C++ 공부중에 생성자때문에 질문 드립니다. ^^; 아래는 소스입니다..

class AAA {
private:
	char* name1;
 
public:
	AAA(const char* _name1) {
		name1 = new char[strlen(_name1)+1];
		strcpy(name1, _name1);
		cout<<"ctor AAA call"<<endl;
	}
 
	virtual ~AAA() {
		delete[] name1;
		cout<<"dtor AAA call"<<endl;
	}
 
	virtual const char* retName(void) const {
		return name1;
	}
};
 
class BBB : public AAA {
private:
	char* name2;
 
public:
	BBB(const char* _name1, const char* _name2) {
		name2 = new char[strlen(_name2)+1];
		strcpy(name2, _name2);
		AAA(_name1);
		cout<<"ctor BBB call"<<endl;
	}
 
	~BBB() {
		delete[] name2;
		cout<<"dtor BBB call"<<endl;
	}
 
	const char* retName(void) const {
		return name2;
	}
};

제가 궁금한것은

이중에서 Class B의 생성자 부분에 보면 AAA(_name1); 다음과 같은 문장이 있는데
이부분때문에 자꾸 다음과 같은 에러가 납니다.

Error 2 error C2512: 'AAA' : no appropriate default constructor available

적절한 기본 생성자가 없다는 이야기인데, 저는 인자로 char* 주었고, AAA에도 합당한 생성자가 있는데
왜 기본 생성자를 찾는것인지 잘 모르겠습니다 ^^;

이부분을 다음과 같이 이니셜라이져를 이용해서 고치면 컴파일이 되는데 그러한 이유도 잘 모르겠습니다..ㅠ_ㅠ

BBB(const char* _name1, const char* _name2) : AAA(_name1) {
		name2 = new char[strlen(_name2)+1];
		strcpy(name2, _name2);
		cout<<"ctor BBB call"<<endl;
	}

읽어주셔서 감사합니다..

buelgsk8er의 이미지

C++에서 상속받은 상위 클래스를 초기화하는 방법은, 이미 아시는 것처럼 initialization-list에서 상위 클래스 타입 이름을 써서 합니다. 두번째 코드처럼 하는 것이 맞지요. 다만 첫번째 예제에서 에러가 나는 것은, BBB 생성자 본문 중의

AAA(_name1);

이 부분 때문에 에러가 나는 것이 아니고, BBB의 initialization list 중에서 적절한 AAA의 호출자를 찾을 수 없기 때문에 나는 것입니다. 즉, 두번째 코드의

: AAA(_name1)

처럼 initialization list에서 explicit하게 상위클래스의 생성자를 호출하지 않으면, 컴파일러는 implicit하게

: AAA()

라는 default constructor를 호출하게 됩니다. 즉, 마치 BBB의 생성자가

BBB(const char* _name1, const char* _name2) : AAA () { // AAA의 default constructor 호출
           .... 
}

처럼 되어 있는 효과를 내는 것이죠. 그러나 AAA에는 저렇게 호출될 수 있는 default constructor가 정의되어있지 않으므로,

Error 2 error C2512: 'AAA' : no appropriate default constructor available

라는 에러가 발생하는 것입니다.

참고로 BBB 생성자 본문 중의

AAA(_name);

이 부분은, 아마도 의도와는 다른 작용을 할 것입니다. 그것은 AAA타입의 (이름없는) 임시객체를 문맥 상에(아마도 스택에, 혹은 레지스터에) 잠깐 생성했다가 곧바로 삭제하는 효과를 냅니다. 다음과 같은 예를 고려해보세요:

using namespace std;
void foo() {
    print_string( string('abc') ); // 이름없는 임시객체가 문맥 중에 생성되서 print_string() 호출 시 넘겨졌다가, 소멸됩니다
    string('abc');   // 이름없는 임시객체가 문맥 중에 생성되었다가 그냥 소멸됩니다.
}
anster의 이미지

아..생성자를 호출하는것이 아니라 그냥 임시 객체 생성 수 바로 소멸로 해석될 수도 있겠군요.. ㅠ_ㅠ 친절한 답변 감사드립니다. 앞으로 상위 클래스는 명심해서 이니셜라이저를 이용해서 초기화 하겠습니다 ^^;; 감사합니다

===================

복군의 이글루
http://anster.egloos.com

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.