Skip to content

Commit

Permalink
memory arithmetics classwork
Browse files Browse the repository at this point in the history
  • Loading branch information
grayed committed Mar 15, 2022
1 parent 2ace867 commit 212919e
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 19 deletions.
1 change: 1 addition & 0 deletions classwork/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@

add_executable (classwork "main.cpp" "main.h")
add_executable (vehicles "vehicle.cpp" "vehicle.h")
add_executable (memarith "memarith.cpp" "memarith.h")

# TODO: Add tests and install targets if needed.
19 changes: 0 additions & 19 deletions classwork/main.cpp
Original file line number Diff line number Diff line change
@@ -1,25 +1,6 @@
#include <iostream>
using namespace std;

class A {
string a_s;
friend int main();
public:
string getBString() const { /* TODO: return B::b_s value */; }
};
class B : public A {
string b_s;
friend int main();
public:
B() { b_s = "It's b!"; }
};

int main()
{
B b;
A *a = &b;
cout << "b address is " << &b << ", a_s address is " << &b.a_s << ", b_s address is " << &b.b_s << endl;
cout << "b size is " << sizeof(b) << ", a_s size is " << sizeof(b.a_s) << endl;
cout << "b_s is '" << a->getBString() << "'" << endl;
return 0;
}
14 changes: 14 additions & 0 deletions classwork/memarith.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#include <iostream>
#include "memarith.h"

using namespace std;

int main()
{
B b;
A *a = &b;
cout << "b address is " << &b << ", a_s address is " << &b.a_s << ", b_s address is " << &b.b_s << endl;
cout << "b size is " << sizeof(b) << ", a_s size is " << sizeof(b.a_s) << endl;
cout << "b_s is '" << a->getBString() << "'" << endl;
return 0;
}
27 changes: 27 additions & 0 deletions classwork/memarith.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <string>

class A {
std::string a_s;
int foo;

friend int main(); // for debugging display purposes

public:
std::string getBString() const { return *((const std::string *)(this + 1)); }
float getBData(int idx) const { return ((const float *)((const std::string *)(this + 1)))[idx]; }
};

class B : public A {
std::string b_s;
float data[7];

friend int main(); // for debugging display purposes

public:
B() { b_s = "It's b!"; }
};

// | class B
// | class A | self |
// | a_s; foo | b_s |
// адрес b_s = адрес b плюс смещение b_s относительно начала b = адрес b плюс размер A

0 comments on commit 212919e

Please sign in to comment.