jasonkim
jasonkim

Reputation: 706

derived class member function failed in c++

To make long story short:

class A {
        public:
              A();
              ~A();
              void SetID(char* ID);
              char* GetID();
        protected:
              char ID[10];
};

class B: public A {
        public:
              B();
              ~B();
        protected:
              ...
        private:
              ...
};

Then in main:

 ...
 B *temp = new B;
 temp->SetID("0x12345678");
 ...

Then the compiler said "Expected constructor,destructor or type conversion before -> token" where "temp->SetID("0x12345678")" lies

Anyone gimme some hints??

Whole Program as Loki suggested:

  #include <iostream>

  using namespace std;

  class A {
      public:
         A();
         ~A();
         void SetID(char* id);
         char* GetID();
       protected:
            char ID[10];
   };

   void A::SetID(char* id){
         strcpy(ID,id);          
    }
    char* A::GetID(){
         return ID;
    }
    class B: public A {
             public:
                 B();
                ~B();
             protected:
                int num;
     };


    int main(){
    B *temp = new B;
    B->SetID("0x12345678");
    cout<<B->GetID()<<endl;

    return 0;
    }

Upvotes: 0

Views: 84

Answers (2)

CB Bailey
CB Bailey

Reputation: 791849

You are using B, which is a type, where you probably meant to use temp which is the name of the variable.

Instead of:

int main(){
B *temp = new B;
B->SetID("0x12345678");
cout<<B->GetID()<<endl;

return 0;
}

You probably meant:

int main(){
B *temp = new B;
temp->SetID("0x12345678");
cout<<temp->GetID()<<endl;

return 0;
}

which is more like the "excerpt" that you posted.

Upvotes: 1

Jirka Hanika
Jirka Hanika

Reputation: 13529

Let me guess.

You have closed main by an unpaired curly brace before you got to this code that you believe is in main. So it is outside of any function, and that is no place for expressions other than initializers.

Upvotes: 0

Related Questions