Segmentation error in simple inheritance related code - c++

Shortened code I wrote for learning purposes. Still the way it is, it doesn't work properly.
Removing last line (&&) it works OK, but with it, code doesn't reach line noted as ##, expressing
segmentation error, after the "BazOnly" text displayed.
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
namespace nek{
class Baz{
int num;
std::string str;
public:
Baz(){cout<<"BazOnly"<<endl;}
string setstr(string& val){
//str.assign(val);
num= 7;
}
};
}
namespace drg{
class Deriv: nek::Baz{
public:
Deriv(char ch){cout<<"DerivChar"<<endl;}
};
};
int main(){
nek::Baz b;
string priv{"zik"};
b.setstr(priv);
cout<<"Passed here"<<endl; //##
drg::Deriv dc{'A'}; // &&
}
Compiled with g++ (option std=gnu++11), Ubuntu 16 on Virtual Box.
Question is what could be the reason for such behavior ?

string setstr(string& val){
//str.assign(val);
num= 7;
}
This method is declared as returning a std::string, but nothing actually gets returned from it. This is undefined behavior.
Most modern C++ compilers will warn you about this. If yours' did, this is an example of why you cannot ignore warning messages from your compiler, even if it did successfully compile your code.

Related

c++ namespace class conflict

i have named this as next.h and included in main.cpp snippet
i have created two libraries one for the main function and the other just for having classes
i wanted to practise for OOPS so i suddenly thought of using namespaces to know their full potential but i am getting confused between why it isnt working as intended
#include<bits/stdc++.h>
namespace custom
{
class aries
{
public:
int data;
};
}
namespace custom2
{
class aries
{
public:
double data1;
};
}
#include<bits/stdc++.h>
#include "next.h"
using namespace std;
using namespace custom;
using namespace custom2;
int main()
{
custom2::aries a;
a.data1=5.000;
cout<<a.data1;
return 0;
}
The output for the following program is as follows:
5
...Program finished with exit code 0
Press ENTER to exit console.
My question is it should have been 5.000 but why it is int type and not a double type ?
Okay, just summing up the comments:
don't use the #include <bits/stdc++.h>. Instead, just include every header you need to use in your code separately. Reason: bad code readability and not every compiler supports this directive. More: Why should I not #include <bits/stdc++.h>?
also don't use the using namespace *name* command. For clarity: you can use namespaces, just don't use using, use *namespace name*:: instead, like std::cout. Reason: bad code readability, also you can mess up with names (like when you have function_name function and the namespace also has a function with the same name, then the compiler will not know which to use (or you get an error).
answer to your question: std::cout omits zeros while printing numbers so 5.00 will be just 5, but 5.278 will be 5.278.

Segmentation fault about c++ smart pointers?

Hello I'm a fresh man to c++. And today when I test a project of my code, I encountered a problem that made me feel confused.
I want to use smart pointer in my project of parse JSON, so I pass a line of string to the class: json_content, and I want the member of json_content, json_value to get the string. The compiler didn't give me any warning or error, but when I run the a.out file, it tells me that segmentation fault. I searched a lot in Google, however I didn't find any solutions to this problem. Could any one help me? Thanks a lot! :)
BTW, my OS is MacOSX x86_64-apple-darwin18.2.0, compiler is Apple LLVM version 10.0.0 (clang-1000.10.44.4)
Here is the code:
#include <string>
#include <iostream>
#include <memory>
#include <typeinfo>
using namespace std;
class json_content {
public:
string json_value;
};
int main()
{
shared_ptr<json_content> c;
shared_ptr<string> p2(new string("this is good"));
// segmentation fault
c->json_value = *p2;
// this is also bad line!
c->json_value = "not good, too!";
return 0;
}
By default, a shared_ptr is nullptr (see API). You can't de-reference a nullptr. You need to initialize c first:
#include <string>
#include <iostream>
#include <memory>
#include <typeinfo>
using namespace std;
class JsonContent {
public:
string json_value;
};
int main() {
shared_ptr<JsonContent> c = std::make_shared<JsonContent>();
shared_ptr<string> p2 = std::make_shared<string>("This is good.");
c->json_value = *p2;
c->json_value = "This is also good!";
cout << c->json_value << endl;
return 0;
}
Demo: http://cpp.sh/5fps7n.

Unable to call member functions

I'm pretty sure I'm probably doing something stupid, but I've been at this an hour and a half and can't figure out what I'm missing.
I can create an object from my class using the default constructor, but can't use an overloaded constructor when I add one. I can't call the print member function that I have included or any others that I have tried to include either. I have put the three files into a Code::Blocks project and gotten the same result. I have also tried the three files on Dev-Cpp with the same result. Any help would be greatly appreciated.
Main Function
#include <iostream>
#include "Appt.h"
using namespace std;
int main()
{
Appt a();
a.print();
}
Appt.h
#ifndef APPT_H
#define APPT_H
#include <iostream>
#include <string>
using namespace std;
class Appt
{
public:
Appt();
void print();
private:
string description;
};
#endif // APPT_H
Appt.cpp
#include "Appt.h"
using namespace std;
Appt::Appt()
{
description = "No Description";
}
void Appt::print()
{
cout << description << endl;
}
I am using Code::Blocks 16.01 with the GCC compiler. These files are not currently in a project. I am also running Windows 7.
It looks like your problems may be related to this line:
Appt a();
Unfortunately, while this looks like it calls the default constructor, it actually declares a to be of type Appt(), that is, a function taking no arguments and returning Appt. If you want to call the default constructor, there are a few options:
Appt a;
Appt a = Appt();
Appt a{}; // requires C++11
I would prefer the last one.

C++: Type casting operator overloading - Visual studio 2013 internal error

I was overloading type casting operators, and internal error has occurred in Visual Studio 2013.
This is the header of the exponent class:
#pragma once
#include "Calc.h"
#include <iostream>
using namespace std;
class Exponent
{
private:
int base;
int exponent;
public:
Exponent();
Exponent(int a)
{
base = a;
}
int getBase()
{
return base;
}
};
void printExp(Exponent e)
{
cout << e.getBase() << endl;
}
and this is calc.h I wrote that will contain overloaded type casting function:
#pragma once
#include "Exponent.h"
class Calc
{
private:
int acc;
public:
Calc();
Calc(int a);
operator Exponent() //this is where I get an error.
{
return Exponent(acc);
}
};
And here's the main function:
#include "stdafx.h"
#include <iostream>
#include "Exponent.h"
#include "Calc.h"
using namespace std;
int main()
{
Calc c(6);
printExp(c);
return 0;
}
I have no idea why I get an error here:
operator Exponent() //this is where I get an error.
{
return Exponent(acc);
}
This is somehow making Visual Studio crash, showing an error like this:
Microsoft(R) C\C++ Optimizing compiler has stopped working...
An internal compiler error (ICE) is a compiler bug—a well-functioning compiler should always report sensible errors for erroneous code. I'd suggest you file a bug report on connect.microsoft.com.
However, you do have a clear problem with your code: you have a circular dependency between your two header files. Exponent.h includes Calc.h, which in turn includes Exponent.h. Even if the compiler weren't crashing with an ICE, it would still report an error (likely of the "undefined symbol" variety) with this code.
There's a simple fix to this case—because Exponent.h doesn't actually have any dependencies on Calc.h, you can just remove the #include "Calc.h" line from Exponent.h, and the circular dependency will be gone.
This code no longer crashes in Visual Studio "14" CTP.
It won't compile because you included Calc.h in Exponent.h, which means the compiler sees class Calc before it sees class Exponent, so you're trying to define a conversion operator to a type that the compiler doesn't know exists yet.

Using private variable in class

I'm running into an irritating problem where my program keeps crashing if I try to reference a private variable that I have created in one of my classes. I can't figure out where I am going wrong. Here is the class that calls the class that crashes:
#include <stack>
#include <fstream>
#include <ostream>
#include <cstdlib>
#include <string>
#include <set>
#include "schemeList.cpp"
using namespace std;
class dataLog
{
public:
stack<string> commands;
set<string> domain;
processor tokens;
int nextToken;
schemeList * s;
dataLog(stack<string> s, ofstream * out, processor p, int location)
{
commands = s;
tokens = p;
nextToken = location;
commands.push("<Query List>");
commands.push(":");
commands.push("Queries");
commands.push("<Rule List>");
commands.push(":");
commands.push("Rules");
commands.push("<Fact List>");
commands.push(":");
commands.push("Facts");
commands.push("<Scheme List>");
commands.push(":");
commands.push("Schemes");
checkNext();
}
void checkNext()
{
for(int i = 0; i < tokens.tags.size(); i++)
{
if(commands.top().compare(tokens.tags[i].getName())!=0)
{
if(commands.top().find("<")==0)
{
if(commands.top().compare("<Scheme List>")==0)
{
int output = (*s).process(i, tokens, domain); string hi = (*s).toString();
}
}
}
commands.pop();
}
}
};
This class creates an object of my SchemeList class, which is written out as follows:
#include "schemes.cpp"
#include <cstdlib>
#include <string>
#include <set>
using namespace std;
class schemeList
{
private:
string success;
public:
int process(int number, processor p, set<string> domain)
{
success = "HELLO";
return 13;
}
string toString()
{
return success;
}
};
As soon as I get to line 15 success = "HELLO";, the program crashes with the message
Unhandled exception at 0x00E48B66 in lab2.exe: 0xC0000005: Access violation reading
location 0xCCCCCCE4.
I am using Microsoft Visual Studio Express 2012 for Windows Desktop.
First off, the variable schemeList * dataLog::s is never initialized, so accessing it is undefined behavior, which leads to the crash. Most likely calling process on a dangling pointer and attempting to write into some memory you don't own.
Second, don't #include "schemeList.cpp". You're not supposed to include cpp files. Rather, separate declarations & implementations and include a header.
You have not initialized dataLog::s. When you call (*s).process(i, tokens, domain), you get undefined behavior.
Firstly, you're apparently including source code files in headers. This will likely break the one definition rule and go horribly wrong.
Secondly, 's' is not a very good name for a class member. It makes it almost impossible to find uses of it.
Thirdly, I can see nowhere in your code that initialises s. I can see where it gets referenced OK, but as it hasn't been initialised, the effect of dereferencing is undefined, and with luck will merely crash your program, which looks like what is happening.