I find one of the most time-consuming compiler errors for me is «cannot instantiate abstract class,» since the problem is always that I didn’t intend for the class to be abstract and the compiler doesn’t list which functions are abstract. There’s got to be a more intelligent way to solve these than reading the headers 10 times until I finally notice a missing «const» somewhere. How do you solve these?
asked Nov 9, 2009 at 5:23
1
cannot instantiate abstract class
Based on this error, my guess is that you are using Visual Studio (since that’s what Visual C++ says when you try to instantiate an abstract class).
Look at the Visual Studio Output window (View => Output); the output should include a statement after the error stating:
stubby.cpp(10) : error C2259: 'bar' : cannot instantiate abstract class
due to following members:
'void foo::x(void) const' : is abstract
stubby.cpp(2) : see declaration of 'foo::x'
(That is the error given for bdonlan’s example code)
In Visual Studio, the «Error List» window only displays the first line of an error message.
answered Nov 9, 2009 at 5:35
James McNellisJames McNellis
344k75 gold badges906 silver badges975 bronze badges
C++ tells you exactly which functions are abstract, and where they are declared:
class foo {
virtual void x() const = 0;
};
class bar : public foo {
virtual void x() { }
};
void test() {
new bar;
}
test.cpp: In function ‘void test()’:
test.cpp:10: error: cannot allocate an object of abstract type ‘bar’
test.cpp:5: note: because the following virtual functions are pure within ‘bar’:
test.cpp:2: note: virtual void foo::x() const
So perhaps try compiling your code with C++, or specify your compiler so others can give useful suggestions for your specific compiler.
AStopher
4,08511 gold badges51 silver badges72 bronze badges
answered Nov 9, 2009 at 5:26
bdonlanbdonlan
221k29 gold badges264 silver badges321 bronze badges
C++Builder tells you which method is abstract:
class foo {
virtual void x() const = 0;
};
class bar : public foo {
virtual void x() { }
};
new bar;
[BCC32 Error] File55.cpp(20): E2352 Cannot create instance of abstract class 'bar'
[BCC32 Error] File55.cpp(20): E2353 Class 'bar' is abstract because of 'foo::x() const = 0'
answered May 30, 2013 at 23:16
Remy LebeauRemy Lebeau
536k30 gold badges444 silver badges750 bronze badges
I find one of the most time-consuming compiler errors for me is «cannot instantiate abstract class,» since the problem is always that I didn’t intend for the class to be abstract and the compiler doesn’t list which functions are abstract. There’s got to be a more intelligent way to solve these than reading the headers 10 times until I finally notice a missing «const» somewhere. How do you solve these?
asked Nov 9, 2009 at 5:23
1
cannot instantiate abstract class
Based on this error, my guess is that you are using Visual Studio (since that’s what Visual C++ says when you try to instantiate an abstract class).
Look at the Visual Studio Output window (View => Output); the output should include a statement after the error stating:
stubby.cpp(10) : error C2259: 'bar' : cannot instantiate abstract class
due to following members:
'void foo::x(void) const' : is abstract
stubby.cpp(2) : see declaration of 'foo::x'
(That is the error given for bdonlan’s example code)
In Visual Studio, the «Error List» window only displays the first line of an error message.
answered Nov 9, 2009 at 5:35
James McNellisJames McNellis
344k75 gold badges906 silver badges975 bronze badges
C++ tells you exactly which functions are abstract, and where they are declared:
class foo {
virtual void x() const = 0;
};
class bar : public foo {
virtual void x() { }
};
void test() {
new bar;
}
test.cpp: In function ‘void test()’:
test.cpp:10: error: cannot allocate an object of abstract type ‘bar’
test.cpp:5: note: because the following virtual functions are pure within ‘bar’:
test.cpp:2: note: virtual void foo::x() const
So perhaps try compiling your code with C++, or specify your compiler so others can give useful suggestions for your specific compiler.
AStopher
4,08511 gold badges51 silver badges72 bronze badges
answered Nov 9, 2009 at 5:26
bdonlanbdonlan
221k29 gold badges264 silver badges321 bronze badges
C++Builder tells you which method is abstract:
class foo {
virtual void x() const = 0;
};
class bar : public foo {
virtual void x() { }
};
new bar;
[BCC32 Error] File55.cpp(20): E2352 Cannot create instance of abstract class 'bar'
[BCC32 Error] File55.cpp(20): E2353 Class 'bar' is abstract because of 'foo::x() const = 0'
answered May 30, 2013 at 23:16
Remy LebeauRemy Lebeau
536k30 gold badges444 silver badges750 bronze badges
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
// абстрактный класс таблицы произволного вида class abstractTable { protected: char fileName[20];// Имя файла char Name[20];// Фамилия и инициалы char Result[10];// Массив с результатами посещения и сдачи лабораторных работ void HeaderC1() //построение шапки таблицы при помощи Си { printf("n ЪДДДДДДДДДДДДДДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДї"); printf("n і F.I.O. і Lab.# 1 і Lab.# 2 і Lab.# 3 і Lab.# 4 і Lab.# 5 і"); printf("n і ГДДДДВДДДДЕДДДДВДДДДЕДДДДВДДДДЕДДДДВДДДДЕДДДДВДДДДґ"); printf("n і і P. і S. і P. і S. і P. і S. і P. і S. і P. і S. і"); } void HeaderC2() // построение шапкм таблицы при помощи С++ { cout<<endl<<"ЪДДДДДДДДДДДДДДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДї"; cout<<endl<<"і F.I.O. і Lab.# 1 і Lab.# 2 і Lab.# 3 і Lab.# 4 і Lab.# 5 і"; cout<<endl<<"і і P. і S. і P. і S. і P. і S. і P. і S. і P. і S. і"; } int ProverkaC1(FILE *fp) // проверка файла для Си { if(fp == NULL) { printf(" n Oshibka otkritiya fayla!n Press any key..."); /*_getch(); //функция возвращает код при нажатии любой клавиши*/ return 0; } return 1; } int ProverkaC2i(ifstream &iFile) // проверка чтения файла в С++ { if(!iFile) { cout<<endl<<"Fayl ne nayden!"<<endl<<"Press any key..."; cin.get(); //читает символ перевода строки return 0; } return 1; } int ProverkaC2o(ofstream &oFile) /* проверка записи в С++, вместо этого можно использовать fstream который объединяет первое со вторым*/ { if(!oFile) { cout<<endl<<"Oshibka otkritiya fayla!"<<endl<<"Press any key..."; /* _getch();//Возвращает код символа нажатой клавиши*/ return 0; } return 1; } // Пустые виртуальные функции. virtual void RecordTablC1(char) = 0;// Запись таблицы средствами С virtual void RecordTablC2(char) = 0;// Запись таблицы средствами С++ virtual void ReadPTablC1(char) = 0;// Чтение таблицы средствами С virtual void ReadPTablC2(char) = 0;// Чтение таблицы средствами С++ }; class Tabl: public abstractTable //класс таблицы { public: Tabl(){} //конструктор /*Перегрузки операций помещения в поток и выбор из потока.*/ friend ofstream& operator << (ofstream &outf, Tabl MyTabl) //объявляем дружественную функцию перегружаем операцию << вывода { outf << endl << MyTabl.Name << " " << MyTabl.Result; return outf; } // Для чтения из файла. friend ifstream& operator >> (ifstream &inf, Tabl &MyTabl) { inf >> MyTabl.Name >> MyTabl.Result; return inf; } // Для вывода на экран. friend ostream &operator << (ostream &out, Tabl MyTabl) { cout<<endl<<" ГДДДДДДДДДДДДДДДДДДДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДґ" <<endl<<" і"<<setiosflags(ios::left)<<setw(22)<<MyTabl.Name <<"і "<<setw(2)<<MyTabl.Result[0]<<"і "<<setw(2)<<MyTabl.Result[1] <<"і "<<setw(2)<<MyTabl.Result[2]<<"і "<<setw(2)<<MyTabl.Result[3] <<"і "<<setw(2)<<MyTabl.Result[4]<<"і "<<setw(2)<<MyTabl.Result[5] <<"і "<<setw(2)<<MyTabl.Result[6]<<"і "<<setw(2)<<MyTabl.Result[7] <<"і "<<setw(2)<<MyTabl.Result[8]<<"і "<<setw(2)<<MyTabl.Result[9] <<"і "; return out; } //Для ввода в таблицу. friend istream &operator >> (istream &in, Tabl &MyTabl) { cout<<endl<<" F.I.O. studenta: "; in>>MyTabl.Name; // записывает именна for (int i=0;i<=9;) { cout<<" Posehenie Lab# "<<i/2+1<<"."; in>>MyTabl.Result[i]; while (MyTabl.Result[i]!='-'&& MyTabl.Result[i]!='+') in>>MyTabl.Result[i]; i++; cout<<" Vipolnenie Lab# "<<i/2+1<<"."; in>>MyTabl.Result[i]; while(MyTabl.Result[i]!='-'&&MyTabl.Result[i]!='+') in>>MyTabl.Result[i]; i++; } return in; } /*Запись таблицы средствами Си*/ void RecordTablC1(char Choice) { FILE *fp;// Указатель на поток. system("cls"); // очистка экрана /*printf("n***********************************");*/ printf("n Zapis' tablici sredstvami yazika C.n"); // вывод на экран /*printf("n***********************************");*/ printf("n Vvedite imya fayla!n "); // вывод на экран scanf("%s", fileName); fp=fopen(fileName, "a"); // Создание или открытие существующего файла if(ProverkaC1(fp)==0) return; // Проверка открытия файла // Ввод данных. while(1) // цикл будет повторятся пока истино { system("cls"); // очистка экрана /*printf("n***********************************");*/ printf("n Zapis' tablici sredstvami yazika C.n"); /*printf("n***********************************");*/ printf("n Vvod dannikh.n"); // вывод на экран ввод данных printf(" n F.I.O. studenta: ");// Ввод Ф.И.О. студента scanf("%s", Name); // сохранание введенных данных в массив имени for(int i=0; i<=9; i++)// Ввод данных по посещению и сдаче лабораторных работ { printf("n Posehenie Lab# %d. ",i/2+1); Result[i] = _getch(); // результат равен символу введенной с клавиатуры while(Result[i]!='-' && Result[i]!='+') Result[i]=_getch(); // пока символ не равен + или - то рузельтат будет равен символу введенного с клавиатуры printf(" %c ", Result[i]); // вывод результата посещения л.р. i++; printf("n Vipolnenie Lab# %d. ",i/2+1); Result[i] = _getch(); // результат равен символу введенной с клавиатуры while(Result[i] !='-'&& Result[i] !='+') Result[i]=_getch();// пока символ не равен + или - то рузельтат будет равен символу введенного с клавиатуры printf(" %c ", Result[i]); // вывод результата выполнения л.р. } fprintf(fp, "n%s %s", Name, Result);// Печать введѐнных данных в файл printf( " nn Prodolzhit' vvod?(Y/N)n" );// Запрос на продолжение ввода.; Choice = _getch(); while(Choice !='y' && Choice !='Y' && Choice !='n' && Choice !='N') Choice=_getch(); // пока Choice не равен всем перечисленным буквам он будет равен введенному символу if(Choice == 'n'||Choice == 'N') break; // если Choice равен n или N то выход из цикла } fclose(fp);// Закрытие файла return; } //Запись таблицы средствами С++ void RecordTablC2(char Choice) //функция записи таблицы С++ { system("cls"); // очистка экрана /*cout<<endl<<"*************************************"<<endl;*/ cout<<" Zapis' tablici sredstvami yazika C++."<<endl; // вывод на экран /*cout<<endl<<"*************************************"<<endl;*/ cout<<endl<<" Vvedite imya fayla!"<<endl<<" ";// Ввод названия файла cin>>fileName; ofstream oFile(fileName, ios::app);// Создание потока if(ProverkaC2o(oFile) == 0) return;// Проверка while(1) // бесконечный цикл пока не истино { system( "cls" ); //очистка /*cout<<endl<<"*************************************"<<endl;*/ cout << endl << " Zapis' tablici sredstvami yazika C++" << endl; /*cout<<endl<<"*************************************"<<endl;*/ // Ввод данных cin>>*this; // Запись в таблицу oFile<<*this; cout<<endl<<endl<<" Prodolzhit' vvod?(Y/N)"<<endl; //завершение программы Choice =_getch(); while(Choice !='y'&& Choice!='Y'&& Choice!='n'&& Choice!='N') Choice=_getch();// пока Choice не равен всем перечисленным буквам он будет равен введенному символу if(Choice == 'n'||Choice == 'N') break;// если Choice равен n или N то выход из цикла } oFile.close(); return; //Закрытие файла. } //Чтение таблицы средствами Си void ReadTablC1(char Choice) { FILE *fp;// Указатель на поток. system("cls"); // очистка /*printf("n***********************************");*/ printf( "n Chteniye tablici sredstvami yazika C.nt" ); /*printf("n***********************************");*/ printf( "n Vvedite imya fayla.n " );// Ввод имени файла scanf("%s", fileName); if((fp=fopen(fileName, "r"))==NULL) if(ProverkaC1(fp)==0) return; // Проверка открытия файла fp=fopen(fileName,"r"); // Открытие файла в случае существования HeaderC1(); // Вывод заголовка таблицы // Вывод строк до конца файла while(!feof(fp)) //Возвращает значение true (истина), если достигнут конец файла { fscanf(fp,"n %s %s", Name, Result); //чтение printf("n ГДДДДДДДДДДДДДДДДДДДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДґ"); //вывод Ф.И.О. и результаты по очереди printf("n і %-20.20s і %2c і %2c і %2c і %2c і %2c і %2c і %2c і %2c і %2c і %2c і", Name, Result[ 0 ], Result[ 1 ], Result[ 2 ], Result[ 3 ], Result[ 4 ], Result[ 5 ], Result[ 6 ], Result[ 7 ], Result[ 8 ], Result[ 9 ] ); } printf("n АДДДДДДДДДДДДДДДДДДДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДЩ"); fclose(fp); // Закрытие файла printf("nn Nazmite na lubuyu klavishu..."); Choice=_getch(); return; } //Чтение таблицы средствами С++ void ReadTablC2(char Choice) { system("cls"); // очистка /*cout<<endl<<"*************************************"<<endl;*/; cout<<" Chteniye tablici sredstvami yazika C++n"; /*cout<<endl<<"*************************************"<<endl;*/ cout<<endl<<" Vvedite imya fayla!"<<endl<<" "; // Ввод названия файла cin>>fileName; ifstream iFile(fileName, ios::app); // Создание потока if(ProverkaC2i(iFile) == 0) return; // Проверка HeaderC2(); // печать заголовка таблицы char endF='0'; // создаем переменную типа char и присваиваем ему 0 while(endF!=EOF)//eof определяет достижение конца файла возвращает 1 если текущая позиция конец файла иначе 0 если возвращает -1 значит ошибка { iFile>>*this; cout<<*this; endF=iFile.peek(); //Функция peek() возвращает следующий символ из потока ввода } cout<<endl<<" АДДДДДДДДДДДДДДДДДДДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДЩ"<<endl<<endl<<" Press any key..."; Choice = _getch(); iFile.close(); // закрытие файла return; } ~Tabl(){}// деструктор }; int main() { // Вспомогательные переменные: int z = 1; // для выхода из программы; char a, b, c, Choice; // переменные для выбора пунктов. Tabl MyTabl; // создание объекта класса do //условие { system("cls"); // очистка printf("n***********n"); printf("tMain menu.nn 1)Vibor deystviya.nn 2)Exit.nn"); // вывод меню и пунктов printf("n***********n"); a=_getch(); // переменная а равняется значению введенной с клавиатуры if(a=='1'||a=='2') // если а равен 1 или 2 { //Пункт 1. Выбор действия. if(a=='1'){ z=1; system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); do { // Выбор варианта записи. system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); cout << " 1) Zapisat' tablicu.nn 2) Prochtat' tablicu."; b = _getch(); if(b=='1'||b == '2') { if(b=='1') { z = 2; while(z==2) { system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); cout <<"tt1) Zapisat' tablicu.nn"; printf(" 1) Zapisat tablicu sredstvami yazika C;nn 2) Zapisat tablicu sredstvami yazika C++.n"); Choice=_getch(); if(Choice=='1') {MyTabl.RecordTablC1(Choice); z=1;} if(Choice=='2') {MyTabl.RecordTablC2(Choice); z=1;} } } if(b == '2') { // Выбор варианта чтения. z = 2; while(z == 2) { system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); cout << "tt2) Prochtat' tablicu.nn"; printf(" 1) Prochitat' tablicu sredstvami yazika C;nn 2) Prochitat' tablicu sredstvami yazika C++.n"); Choice = _getch(); if(Choice=='1') {MyTabl.ReadTablC1(Choice); z=1;} if(Choice=='2') {MyTabl.ReadTablC2(Choice); z=1;} } } } } while(z!=1); } //Пункт 2. Выход if(a=='2') { z = 2; while((z!=1)&&(z!=0)) { system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); //MyFrameC2; printf("ntExit.n Do you want to quit?(Y\N)n"); c = _getch(); if(c=='y'||c=='Y') z=0; else if(c=='n'||c=='N') z=1; else z=2; } } } } while(z!=0); system("cls");//очистка экрана return 0; } |
- Remove From My Forums
-
Question
-
I’m trying to make a Virtual Constructor Function to return a pointer to a new object; «ServerExt».
My code is:
class ServerExtApp : public ServerExt
{
public:
virtual void execute() throw(ServerExtApp::Exc);
};ServerExt *virtualCtor() throw(ServerExt::Exc, bad_alloc)
{
return new ServerExtApp;
}
but when I compile I get these mistakes:Compiling…
ServerExtApp.cpp
E:VICTORININFITELSCRIPTS_PRUEBAServerExtApp.cpp(94) : error C2259: ‘ServerExtApp’ : cannot instantiate abstract class due to following members:
E:VICTORININFITELSCRIPTS_PRUEBAServerExtApp.cpp(55) : see declaration of ‘ServerExtApp’
E:VICTORININFITELSCRIPTS_PRUEBAServerExtApp.cpp(94) : warning C4259: ‘void __thiscall ServerExt::execute(unsigned long)’ : pure virtual function was not defined
c:program filesmicrosoft visual studiovc98includeserverext.h(156) : see declaration of ‘execute’
E:VICTORININFITELSCRIPTS_PRUEBAServerExtApp.cpp(94) : error C2259: ‘ServerExtApp’ : cannot instantiate abstract class due to following members:
E:VICTORININFITELSCRIPTS_PRUEBAServerExtApp.cpp(55) : see declaration of ‘ServerExtApp’
E:VICTORININFITELSCRIPTS_PRUEBAServerExtApp.cpp(94) : warning C4259: ‘void __thiscall ServerExt::execute(unsigned long)’ : pure virtual function was not defined
c:program filesmicrosoft visual studiovc98includeserverext.h(156) : see declaration of ‘execute’
Error executing cl.exe.ServerExtApp.obj — 2 error(s), 2 warning(s)
How do I correct them?Víctor M.
Answers
-
No: this is not a warning in the true sense of the word: this warning message is really a continuation of the error message that immediately proceeds it. It is telling you, very specifically, that you need to provide an implementatin for the execute(unsigned long) method.
To re-iterate again: you need to provide an implementation for:
void __thiscall ServerExt::execute(unsigned long);
I’m attempting to create a concrete instance of the IAudioEvents COM interface (available in Vista and later). This is my first foray into COM programming, so I’m probably just doing something stupid here. Anyway, the following code fails to compile with «C2259: ‘AudioEndpointVolumeNotifierImpl’ : cannot instantiate abstract class».
Class Definiton (AudioEndpointVolumeNotifierImpl.h):
class AudioEndpointVolumeNotifierImpl : public IAudioSessionEvents
{
private:
LONG _cRef;
public:
AudioEndpointVolumeNotifierImpl() : _cRef(1){}
~AudioEndpointVolumeNotifierImpl(){}
HRESULT STDMETHODCALLTYPE OnSimpleVolumeChanged(float NewVolume, BOOL NewMute,LPCGUID EventContext);
HRESULT STDMETHODCALLTYPE OnChannelVolumeChanged(DWORD ChannelCount, float NewChannelVolumeArray[], DWORD ChangedChannel, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnDisplayNameChanged(LPCWSTR NewDisplayName, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnGroupingParamChanged(LPCGUID NewGroupingParam, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPWCHAR NewIconPath, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason){return S_OK;}
HRESULT STDMETHODCALLTYPE OnStateChanged(AudioSessionState NewState){ return S_OK; }
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&_cRef);
}
ULONG STDMETHODCALLTYPE Release()
{
ULONG ulRef = InterlockedDecrement(&_cRef);
if (0 == ulRef)
{
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface)
{
if (IID_IUnknown == riid)
{
AddRef();
*ppvInterface = (IUnknown*)this;
}
else if (__uuidof(IAudioSessionEvents) == riid)
{
AddRef();
*ppvInterface = (IAudioSessionEvents*)this;
}
else
{
*ppvInterface = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
};
Corresponding .cpp:
HRESULT STDMETHODCALLTYPE AudioEndpointVolumeNotifierImpl::OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext)
{
PostStatusChange(NewVolume);
return S_OK;
}
Fails in an IClassFactory instance on the following code:
...
AudioEndpointVolumeNotifierImpl* pObject = new AudioEndpointVolumeNotifierImpl();
if (pObject == NULL)
{
return E_OUTOFMEMORY ;
}
...
A good portion of this code IS lifted from some tutorials (the IUnknown stuff in particular). I’m not expecting this code to work just yet, but I can’t see why it doesn’t compile.
Thanks.
I’m attempting to create a concrete instance of the IAudioEvents COM interface (available in Vista and later). This is my first foray into COM programming, so I’m probably just doing something stupid here. Anyway, the following code fails to compile with «C2259: ‘AudioEndpointVolumeNotifierImpl’ : cannot instantiate abstract class».
Class Definiton (AudioEndpointVolumeNotifierImpl.h):
class AudioEndpointVolumeNotifierImpl : public IAudioSessionEvents
{
private:
LONG _cRef;
public:
AudioEndpointVolumeNotifierImpl() : _cRef(1){}
~AudioEndpointVolumeNotifierImpl(){}
HRESULT STDMETHODCALLTYPE OnSimpleVolumeChanged(float NewVolume, BOOL NewMute,LPCGUID EventContext);
HRESULT STDMETHODCALLTYPE OnChannelVolumeChanged(DWORD ChannelCount, float NewChannelVolumeArray[], DWORD ChangedChannel, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnDisplayNameChanged(LPCWSTR NewDisplayName, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnGroupingParamChanged(LPCGUID NewGroupingParam, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPWCHAR NewIconPath, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason){return S_OK;}
HRESULT STDMETHODCALLTYPE OnStateChanged(AudioSessionState NewState){ return S_OK; }
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&_cRef);
}
ULONG STDMETHODCALLTYPE Release()
{
ULONG ulRef = InterlockedDecrement(&_cRef);
if (0 == ulRef)
{
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface)
{
if (IID_IUnknown == riid)
{
AddRef();
*ppvInterface = (IUnknown*)this;
}
else if (__uuidof(IAudioSessionEvents) == riid)
{
AddRef();
*ppvInterface = (IAudioSessionEvents*)this;
}
else
{
*ppvInterface = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
};
Corresponding .cpp:
HRESULT STDMETHODCALLTYPE AudioEndpointVolumeNotifierImpl::OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext)
{
PostStatusChange(NewVolume);
return S_OK;
}
Fails in an IClassFactory instance on the following code:
...
AudioEndpointVolumeNotifierImpl* pObject = new AudioEndpointVolumeNotifierImpl();
if (pObject == NULL)
{
return E_OUTOFMEMORY ;
}
...
A good portion of this code IS lifted from some tutorials (the IUnknown stuff in particular). I’m not expecting this code to work just yet, but I can’t see why it doesn’t compile.
Thanks.